C# 調用C++ 結構體示例


C++ 定義

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, "徐滔");
}

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;
}

 

extern "C" __declspec(dllexport) bool InputInfo(int age,char name[20], Stu* stuInfo)
{
stuInfo->Age = age;
char* test = name;
strcpy_s(stuInfo->Name, name);
return true;
}

 

在C# 中需要重新定義結構

[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
public struct Stu
{
public int Age;
[System.Runtime.InteropServices.MarshalAs(UnmanagedType.ByValTStr,SizeConst =20)]
public string Name;
}

注意c# 中 和c++ 中的數據類型的對應。

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

申明 調用函數

[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);

 

[DllImport("MyFuncDll.dll", EntryPoint = "InputInfo", CallingConvention = CallingConvention.Cdecl,
CharSet =CharSet.Ansi)]

特別要注意 CharSet 屬性的設置。

調用測試

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#中調用C++傳遞 char[]類型的參數

string sna = "系統";
bool b = InputInfo(23, sna, ref stuInfo);

 

//-------------------------------------------------------------

C# 調用 C++ dll返回字符串問題

做個簡單的例子,將傳入的字符串復制后再返回…

C++中定義方法:

EXTERN_C __declspec(dllexport) bool TryCopyStr(char* src, char** desstr)
{
    _memccpy(*desstr, src,0, strlen(src));
     return true;
}

參數: src —源字符串

參數:desstr—目標字符串(也就是要將返回值賦給該參數),注意其類型為 char**

 

C# 代碼:

//dll調用申明

[DllImport("dotNetCppStrTest.dll", EntryPoint = "TryCopyStr", CallingConvention = CallingConvention.Cdecl)]
public extern static bool TryCopyStr(string src,ref StringBuilder desStr);

//測試方法

private void TestTryGetStr()

{

        bool suc = false;
        StringBuilder resultStrBuilder = new StringBuilder();
        string srcStr = "this is string from .net 從.net傳過去的字符串";
        suc = TryCopyStr(srcStr,ref resultStrBuilder);

}

注:

     參數 desStr 是 StringBuilder 類型,而不是 String 類型。因為在dll中對該參數進行了重新賦值,也即是參數值發生了改變,String 類型的值是不能改變的。

     此方法在VS2015測試通過。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM