Using C++ DLL in C# project

那年仲夏 提交于 2019-12-01 05:13:34

try to use __stdcall (or WINAPI or APIENTRY) in the function exported from the DLL.

Try to switch your C# code from AnyCPU to x86 (in Properties dialog).

Your exported function uses the PASCAL calling convention, which in Windows is the same as stdcall. The .Net runtime needs to know about that, so modify your C# method signature as follows:

[DllImport("convert.dll", SetLastError = true, CallingConvention=CallingConvention.StdCall)]
static extern Int32 convert([MarshalAs(UnmanagedType.LPStr)] string filename);

Two main steps involved are

1- Creating a C++ dll

In visual studio

**New->Project->Class Library** in c++ template Name of project here is first_dll in visual studio 2010. Now **declare your function as public** in first_dll.h file and write the code in first_dll.cpp file as shown below.

Header File

Cpp File

Check **Project-> Properties -> Configuration/General -> Configuration Type** 
this option should be **Dynamic Library(.dll)** and build the solution/project now.

first_dll.dll file is created in Debug folder

2- Linking it in C# project

Open C# project

Rightclick on project name in solution explorer -> Add -> References -> Browse to path
where first_dll.dll is created and add the file 

Add this line at top in C# project

Using first_dll; 

Now file can be accessed using below statement in some function

double var = Class1.sum(4,5);

I linked the C++ project .dll created in VS2010 to C# project created in VS2013. It works well.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!