可以看到C++中AddPerson返回了char*,在C#中我们用IntPtr来接,然后用Marshal将指针转换string,接下来用工具生成好的C#代码拷到项目中来,如下:
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct Person { /// char* [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] public string username; /// char* [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] public string password; } class Program { [DllImport("ConsoleApplication1.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] extern static IntPtr AddPerson(Person person); static void Main(string[] args) { var person = new Person() { username = "dotnetfly", password = "123456" }; var ptr = AddPerson(person); var str = Marshal.PtrToStringAnsi(ptr); Console.WriteLine($"username={str}"); Console.ReadLine(); } } ---------- output ------------ username=dotnetfly 4. 回调函数(异步)的处理前面介绍的3种情况都是单向的,即C#向C++传递数据,有的时候也需要C++主动调用C#的函数,我们知道C#是用回调函数,也就是委托包装,具体我就不说了,很开心的是C++可以直接接你的委托,看下怎么实现。
--- Person.cpp extern "C" { //函数指针 typedef void(_stdcall* PCALLBACK) (int result); _declspec(dllexport) void AsyncProcess(PCALLBACK ptr); } --- Person.h #include "Person.h" #include "iostream" using namespace std; void AsyncProcess(PCALLBACK ptr) { ptr(10); //回调C#的委托 }从代码中看到,PCALLBACK就是我定义了函数指针,接受int参数。
class Program { delegate void Callback(int a); [DllImport("ConsoleApplication1.dll", CallingConvention = CallingConvention.Cdecl)] extern static void AsyncProcess(Callback callback); static void Main(string[] args) { AsyncProcess((i) => { //这里回调函数哦... Console.WriteLine($"这是回调函数哦: {i}"); }); Console.ReadLine(); } } ------- output ------- 这是回调函数哦: 10这里我做了一个自定义的delegate,因为我使用Action<T>不接受泛型抛异常(┬_┬)。
四:总结这让我想起来前段时间用python实现的线性回归,为了简便我使用了http和C#交互,这次准备用C++改写然后PInvoke直接交互就利索了,好了,借助C++的生态,让 C# 如虎添翼吧~~~
如您有更多问题与我互动,扫描下方进来吧~