C# 调用 C++/C 接口方法

废话不多说,直接上代码:

1、使用vs创建C++生成DLL的工程

注意要手动添加    extern "C"

#pragma once

#ifdef LIBCAMBRIAN_EXPORTS
#define LIBCAMBRIAN_API extern "C" __declspec(dllexport)
#else
#define LIBCAMBRIAN_API extern "C" __declspec(dllimport)
#endif


typedef void(*recvData)(const char *);   // 定义C++回调函数

LIBCAMBRIAN_API int start(recvData recvFunction); // 设置回调

LIBCAMBRIAN_API int stop(void);

LIBCAMBRIAN_API int send(const char* pMsg);

 

方法自己实现,如果不会,就不要继续看了。

 

2、使用C#调用DLL

新建C#控制台,添加如下代码:

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void callbackHandler([MarshalAs(UnmanagedType.LPStr)]StringBuilder msg); // 消息接收回调

[DllImport("***.dll", EntryPoint = "start", CallingConvention = CallingConvention.StdCall)]
public static extern void start1(callbackHandler recvMsg); // 接口

[DllImport("***.dll", EntryPoint = "stop", CallingConvention = CallingConvention.StdCall)]
public static extern void stop1(); // 接口

[DllImport("***.dll", EntryPoint = "send", CallingConvention = CallingConvention.StdCall)]
public static extern void send1([MarshalAs(UnmanagedType.LPStr)]StringBuilder msg); // 接口
       
static void getMsg([MarshalAs(UnmanagedType.LPStr)]StringBuilder s) // 接受消息回调
{
            Console.WriteLine("回调字符串内容:{0}", s);
            return;
}


 static void Main(string[] args)
{
            start1(getMsg);
            Console.ReadLine();

            StringBuilder sb = new StringBuilder("ABCDEFGHIJKLMN", 50);
            send1(sb);
            Console.ReadLine();

            stop1();
            Console.ReadLine();

            return;
}

运行,即可顺利调用C++接口。

 

你可能感兴趣的:(C# 调用 C++/C 接口方法)