Mar*_*lle 12 c# interop native
在我的C#应用程序中,我想在C中编写一部分代码.我计划编写一个可与.Net互操作的DLL.我怎样才能做到这一点?
Ben*_*igt 20
基本上有三种正确的方法:
extern "C""兼容的API,如Windows API本身.这是最便携的,但对于您的调用者而言,使用类模型来表示对象并不方便.
extern "C" returntype __stdcall __declspec(dllexport) func(params) { ... }并且有一件事绝对不要做:
__declspec(dllexport)C++类.编辑:我还想解释选项#2的一些好的做法,它们将最大限度地提高可移植性,并使原生C/C++部分也可以从非托管应用程序中使用.
使用宏可以使这更容易,通常的做法是:
在头文件中,所有函数声明都是这样的
MYPROJECTAPI(returntype) PublicFunc(params);
Run Code Online (Sandbox Code Playgroud)
在您的项目中,定义是
#define MYPROJECTAPI(returntype) \
extern "C" returntype __stdcall __declspec(dllexport)
Run Code Online (Sandbox Code Playgroud)
在消费者项目中
#define MYPROJECTAPI(returntype) \
extern "C" returntype __stdcall __declspec(dllimport)
Run Code Online (Sandbox Code Playgroud)
然后你可以为不使用的其他编译器(如gcc)定义宏__declspec.
完整的解决方案看起来像(在公共头文件中myproject.h):
#if _WIN32
# if BUILDMYPROJECT
# define MYPROJECTAPI(returntype) \
extern "C" returntype __stdcall __declspec(dllexport)
# else
# define MYPROJECTAPI(returntype) \
extern "C" returntype __stdcall __declspec(dllimport)
# endif
#else
# define MYPROJECTAPI(returntype) extern "C" returntype
#endif
Run Code Online (Sandbox Code Playgroud)
然后BUILDMYPROJECT在构建myproject.dll时将导致您的Visual C++项目被定义
| 归档时间: |
|
| 查看次数: |
10025 次 |
| 最近记录: |