C # calls the C + + struct Body example

Source: Internet
Author: User

C + + definition

typedef struct STU
{
Public
int age;
Char name[20];
};

typedef struct NUM
{
int N1;
int N2;
};

extern "C" __declspec (dllexport) void Findinfo (stu& Stu)
{
Stu. Age = 10;
strcpy_s (Stu. Name, "Xu Xian");
}

extern "C" __declspec (dllexport) int Add (int a,int b)
{
return a + B;
}

extern "C" __declspec (dllexport) int getnumsum (num* Num)
{
return num->n1 + num->n2;
}

Need to redefine structure in C #

[System.Runtime.InteropServices.StructLayout (LayoutKind.Sequential)]
public struct STU
{
public int age;
[System.Runtime.InteropServices.MarshalAs (Unmanagedtype.byvaltstr,sizeconst =20)]
public string Name;
}

Note the correspondence of the data types in C # and C + +.

public struct Num
{
public int N1;
public int N2;
}

Declaring the calling function

[DllImport ("MyFuncDll.dll", EntryPoint = "Findinfo", CallingConvention = Callingconvention.cdecl,
CharSet = CharSet.Unicode)]
extern static void Findinfo (ref Stu STU);
[DllImport ("MyFuncDll.dll", EntryPoint = "Add", CallingConvention = callingconvention.cdecl)]
public extern static int Add (int a, int b);

[DllImport ("MyFuncDll.dll", EntryPoint = "Getnumsum", CallingConvention = callingconvention.cdecl)]
public extern static int getnumsum (ref num num);

Call Test

int re = ADD (1, 3);
num n = new num () {N1 = 1, N2 = 2};
int r = Getnumsum (ref n);
Stu Stu = new Usecppdll.stu ();
Findinfo (ref Stu);
MessageBox.Show (Stu. Name);

C # calls the C + + struct Body example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.