8

C#和C++混合编程的一些tips

 2 years ago
source link: https://blogread.cn/it/article/1618?f=hot1
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

C#和C++混合编程的一些tips

浏览:2959次  出处信息

最近帮朋友写个小东西的时候,刚好用到了C#和C++的混合编程,记录一些tips供日后参考。

首先说明下环境:C#调用C++的库函数,C++建立一个非托管类库项目,C#项目引用之。

1.C++类库中的tips

C++类库中导出函数的声明如下:

extern "C" __declspec(dllexport) int* Detect(char* data,int width,int height);

需要注意的是:

要使用extern "C" 标明,否则C#调用时会找不到方法名;其次要使用__declspec(dllexport)标明为导出函数。

2.C#调用的tips

C#调用时,首先需要声明外部方法的签名,如下:

[DllImport("DetectDll.dll", CallingConvention = CallingConvention.Winapi)]
public extern static void Detect ([MarshalAsUnmanagedType.LPArray,SizeConst=8]byte[] bp,int w,int h,[MarshalAsUnmanagedType.LPArray,SizeConst=4]int[] result);

需要注意的是:

指明CallingConvention为Winapi类型;

对于数组类型需要指明MarshalAs的方式,一般的定长数组或下标有上限的,都可以用LPArray来Marshal。

调用非托管代码需要使用unsafe关键字,对于指针需要进行fixed限制。

建议继续学习:

QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK