Question: Calling C++ Code with a struct from C#

Question

Calling C++ Code with a struct from C#

Answers 1
Added at 2017-11-30 23:11
Tags
Question

I was given a third party library that wraps unmanaged C++ code into a C# api, one of the functions has a parameter that appears to be a struct from the native global namespace how do we create an instance of that struct in C#?

This is the c++ Struct:

struct GroupInfo
{
    int                 cMembers;                                           // Current # of members in the group.
    char                saMembers[cMaxMembers][cMaxLoginID + 1];            // Members themselves.
};

When we try to declare an instance of it in C# the compiler says global::GroupInfo is not available due to its protection level.

c++ signature

int QueryGroup(char* sGroupName,
    GroupInfo& gi);

C# signature

VMIManaged.QueryGroup(sbyte*, GroupInfo*)

I have a class called group info

class GroupInfo
{
    public int cMembers;
    public sbyte[,] saMembers;
}

and when i try to implement that using this code i get a cannot convert error

GroupInfo gi = new GroupInfo();

unsafe
{
    sbyte* grpName;
    fixed (byte* p = groupNameBytes)
    { 
        grpName = (sbyte*)p;
    }
    return vmi.QueryGroup(grpName, gi); // cannot convert from class GroupInfo to GroupInfo*
}
Answers to

Calling C++ Code with a struct from C#

nr: #1 dodano: 2017-11-30 23:11

You are most likely getting the error because of the default protection level of the default constructor in C# for your GroupData class. If it is defined in a different file from the file in which you are trying to use it, defining it like this should work:

class GroupInfo
{
  public GroupInfo() {}
  public int cMembers;
  public sbyte saMembers[cMaxMembers][cMaxLoginID + 1];
};
Source Show
◀ Wstecz