简体   繁体   English

在C#代码中使用cpp dll

[英]using cpp dll in c# code

I'm trying to use native c++ dll inside ac# application. 我正在尝试在ac#应用程序中使用本机c ++ dll。

I followed this article to get started. 我跟着这个文章开始。

Its working fine while the dll using only c files (like in the tutorial), but when using cpp files I cant make it work. 当dll仅使用c文件(如本教程中所述)时,它的工作正常,但是当使用cpp文件时,我无法使其工作。

using the dumpbin tool I can see that my exported function names changed. 使用dumpbin工具,我可以看到导出的函数名称已更改。 for example a function call 'next' changed to '?next@@YAHH@Z' and when I'm trying to call it in the c# code it cant find it. 例如,将函数调用“ next”更改为“?next @@ YAHH @ Z”,当我尝试在c#代码中调用它时,找不到它。

my dll code is: 我的dll代码是:

__declspec(dllexport)
int next(int n)
{
    return n + 1;
}

the c# code C#代码

[DllImport("lib.dll", CallingConvention = CallingConvention.Cdecl)]
    extern static int next(int n);

its the same code while using c file or cpp files 使用c文件或cpp文件时使用相同的代码

Thanks in advance Amichai 在此先感谢Amichai

What you are attempting to do is to make a trampoline function, to externalize the use of your C++ objects. 您正在尝试做一个蹦床功能,以外部化C ++对象的使用。

What you are experiencing is called symbol mangling. 您遇到的情况称为符号错误处理。 It is a c++-specific way of naming the symbols (like the functions) in a dynamic library and an executable, to enable polymorphism. 这是一种c ++特定的方式,可以在动态库和可执行文件中命名符号(如函数),以实现多态。

You have to specify that you want to cancel the mangling effect by using an extern "C" statement in your library code, just like this: 您必须指定要通过使用库代码中的extern "C"语句来取消破坏效果,如下所示:

extern "C" __declspec(dllexport)
int next(int n)
{
    return n + 1;
}

More on this here: Exporting functions from a DLL with dllexport 有关此内容的更多信息:使用dllexport从DLL导出函数

Please provide the Entry Point 请提供入口点

An example below 下面的例子

[DllImport("lib.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "next", CharSet = CharSet.Ansi)]
static extern int next(int n);

Hopefully It helps. 希望它会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM