Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling C++ Code with a struct from C#

Tags:

c++

c#

struct

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*
}
like image 593
user2379915 Avatar asked Nov 30 '17 22:11

user2379915


People also ask

How do you pass a structure to a function in C?

You can also pass structs by reference (in a similar way like you pass variables of built-in type by reference). We suggest you to read pass by reference tutorial before you proceed. During pass by reference, the memory addresses of struct variables are passed to the function.

Can a struct have methods C?

Contrary to what younger developers, or people coming from C believe at first, a struct can have constructors, methods (even virtual ones), public, private and protected members, use inheritance, be templated… just like a class .

Can struct inherit in C?

No you cannot. C does not support the concept of inheritance.


1 Answers

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];
};
like image 191
mnistic Avatar answered Sep 21 '22 16:09

mnistic