Using C++ dll in C# code

0. Environment

Win 8 Pro en 64bit

Visual Studio 2012 en

1. Steps

1.1. In C++ code:

//dll.cpp

extern "C" __declspec(dllexport) double __stdcall Add(double a, double b)

{……}

1.2. In C# code:

[DllImport(".\\DllTest.dll", CallingConvention = CallingConvention.StdCall)]

public static extern double Add(double a, double b);

2. How to use string as parameter and return value

//dll.cpp

//p_inFilePath is an input, and p_outFilePath is an output

extern "C" __declspec(dllexport) void __stdcall Normalizer(char *p_inFilePath, char *p_outFilePath)

//call.cs

[DllImport("PNormalizer.dll")]

private static extern void Normalizer(string inFilePath, StringBuilder outFilePath);



int len = 1024;//this number should be big enough to contain all of output char

StringBuilder outFilePath = new StringBuilder(len);

Normalizer(inFilePath, outFilePath);

3. Something you need to focus on

3.1. You should Rebuild the C++ dll project if you changed it, or you will get the same errors and results after you changed the dll code

4. References

http://hi.baidu.com/yun0216/item/f7c856d227465738e3108fa3

(This article is from http://www.cnblogs.com/chenyineng/archive/2012/12/15/2818889.html, and belongs to http://chenyineng.cnblogs.com and http://www.chenyineng.info)

你可能感兴趣的:(code)