C#之与C/C++语言交互

C#之与C/C++交互

我们先在VS中分别新建一个动态链接库项目(CLibrary)一个C#控制台程序
并且C#控制台程序调用CLibrary中定义的接口

1、C#调用C/C++库中的函数

在pch.cpp添加两个函数

int Add(int a, int b) {

    return a + b;
}
int Minus(int a, int b) {

    return a - b;
}

在pch.h中导出这两个函数

int __declspec(dllexport) Add(int a, int b);
int __declspec(dllexport) Minus(int a, int b);

然后在C#中调用这两个函数

[DllImport("CLibrary.dll", CallingConvention = CallingConvention.Cdecl,EntryPoint = "Add")]
        public extern static int Add(int a, int b);
        [DllImport("CLibrary.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "Minus")]
        public extern static int Minus(int a, int b);


int a = 233;
int b = 314;
int ret = Add(a, b);
int retMinus = Minus(a, b);
Console.WriteLine($"{a} + {b} = {ret}");
Console.WriteLine($"{a} - {b} = {retMinus}");

正常输出为


调用C函数结果.png

这个代码会提示错误
System.EntryPointNotFoundException: 无法在 DLL“CLibrary.dll”中找到名为“Add”的入口点
这一般是在库口找不到该入口点函数
解决方法
通过Dumpbin.exe命令查看Dll导出的函数
dumpbin工具一般VS安装目录下面
在Visual Studio的安装目录下
\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\XXXX\bin\Hostx64\x64
dumpbin.exe /exports CLibrary.dll

dumbpin查看dll导出函数.png

从图中红色框可以看到CLibrary.dll的导出的函数为
?Add@@YAHHH@Z
?Minus@@YAHHH@Z
这是因为这是C++定义的函数所以出现这种乱码符号,这与我们定义的EntryPoint Add/Minus不一致
解决有两个办法
1.修改EntryPoint为这两个符号如下

[DllImport("CLibrary.dll", CallingConvention = CallingConvention.Cdecl,EntryPoint = "?Add@@YAHHH@Z")]
        public extern static int Add(int a, int b);
        [DllImport("CLibrary.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "?Minus@@YAHHH@Z")]
        public extern static int Minus(int a, int b);

2.在pch.h中加入C函数声明方式

#ifdef __cplusplus
extern "C" {
#endif

int __declspec(dllexport) Add(int a, int b);
int __declspec(dllexport) Minus(int a, int b);

#ifdef __cplusplus
}
#endif

C/C++回调C#

C/C++的回调函数对应的C#的类型是delegate
我们还是以C#调用C/C++库中的函数 的工程演示
1、我们在CLibrary中的pch.h定义一个指针函数


typedef void(CALLBACK* Callback)(int msg,const char* buff);
int __declspec(dllexport) TestCallbackFunc(Callback callback);

注意:CALLBACK一定要定义,不然乱七八糟的各种错误
在pch.cpp中定义TestCallbackFunc

int TestCallbackFunc(Callback callback) {

    if (callback) {
        callback(200, "callback from C/C++");
    }
    return 0;
}

2、C#中调用CLibrary的TestCallbackFunc
声明

[DllImport("CLibrary.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "TestCallbackFunc")]
        public extern static int TestCallbackFunc(CallbackDelegate callback);
        /// <summary>
        /// 对应C/C++层的指针函数void(CALLBACK* Callback)(int msg, const char* buff)
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="info"></param>
        public delegate void CallbackDelegate(int msg,string info);

调用

private void processCCallback(string title)
        {
          
            int ret = TestCallbackFunc(new CallbackDelegate(CallbackFromC));
            Console.WriteLine($"TestCallbackFunc ret = {ret}");
        }
        private void CallbackFromC(int a, string buff)
        {
            print($"callback from C a={a},buff={buff}");
        }

注意:赋值delegate的时候一定要new 一个,不然各种乱七八糟的错误
正确输出

C回调C#结果.png

C/C++结构体与C#对应数据结构

在pch.h定义结构体

typedef struct _MsgInfo {
    int msg;
    char buffer[123];
}MsgInfo;
//两个参数主要是为了在C#层验证结构的转换,请注意看C#层
typedef void(CALLBACK* StructCallback)(MsgInfo *msg1,MsgInfo *msg2);
void __declspec(dllexport) TestStructCallback(int msg, StructCallback callback);

pch.cpp中定义

///全局结构体
MsgInfo mMsgInfo;
void  TestStructCallback(int msg,StructCallback callback) {
    memset(&mMsgInfo, 0, sizeof(MsgInfo));
    mMsgInfo.msg = msg;
    const char* buffer = "Transform Struct To C#";
    memcpy(mMsgInfo.buffer, buffer, strlen(buffer) + 1);
    if (callback) {
        //只能够传地址,传递对象会PInvoke错误
        callback(&mMsgInfo, &mMsgInfo);
    }
}

在C#层定义如下
C#层定义和刚才在C/C++定义的结构体MsgInfo对应的结构体Message

//CLibrary.dll中的pch.h中的 MsgInfo
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 4)]
    class Message
    {
        public int msg;
        /// <summary>
        /// SizeConst的值是和MsgInfo中的buffer大小相一致的,其它类型比如数据也要指定该大小
        /// </summary>
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 123)]
        public string buffer;
    }
[DllImport("CLibrary.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "TestStructCallback")]
        private extern static void TestStructCallback(int msg, CallbackStructDelegate callback);
        private delegate void CallbackStructDelegate(IntPtr pMsg,Message msg);
/// <summary>
        /// C/C++结构体转换到C#层可以直接为结构体对象,也可以通过指针转换
        /// </summary>
        /// <param name="pMsg"></param>
        /// <param name="msg"></param>
        private void CallbackStructFromC(IntPtr pMsg,Message msg)
        {
            Message pParam = (Message)Marshal.PtrToStructure(pMsg, typeof(Message));
            Console.WriteLine($"CallbackStructFromC by Struct Type Message.msg = {msg.msg},Message.buffer={msg.buffer}");
            Console.WriteLine($"CallbackStructFromC by Ponter Type Message.msg = {pParam.msg},Message.buffer={pParam.buffer}");
        }

调用如下

TestStructCallback(123,new CallbackStructDelegate(CallbackStructFromC));
            TestStructCallback(456,new CallbackStructDelegate(CallbackStructFromC));

正确输出


C层传递结构体到CSharp层结果.png

C/C++传字符串到C#

在pch.h声明如下
void __declspec(dllexport) OutParamStringFunc(char * sbOut,char* outParam);
在pch.cpp实现如下

    const char* buffer = "Transform string To C#";
void OutParamStringFunc(char* sbOut, char* outParam) {
    memcpy(sbOut, buffer, strlen(buffer) + 1);
    outParam = new char[100];
    memset(outParam, 0, 100);

    memcpy(outParam, buffer, strlen(buffer) + 1);
}

C#声明如下

[DllImport("CLibrary.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "OutParamStringFunc")]
        public extern static void OutParamStringFunc(StringBuilder param,out IntPtr param2);


StringBuilder param = new StringBuilder();
            IntPtr pString;
            OutParamStringFunc(param, out pString);
            string param2 = Marshal.PtrToStringAnsi(pString);
            Console.WriteLine("after OutParamStringFunc  param = " + param + " param2 = " + param2);

以上输出pString一直为空,暂不知道如何处理.
结果如下


C层转字符串到CSharp.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容