DotnetCalling c++ (dll) from c# with an LPCTSTR parameter
2015 · 10 · 15
1 min read
Paper
Contents
An example of calling a c++ dll from c#.
First, some simple c++ code.
test.h
1
| extern "C" __declspec(dllexport) int test(LPCTSTR szFileName);
|
test.cpp
1
2
3
| int test(LPCTSTR szFileName) {
return 0;
}
|
Next, the c# side
1
2
3
4
5
6
7
8
9
| [DllImport("sampleLib.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int test( [MarshalAs(UnmanagedType.LPWStr)] string szFileName);
private void button2_Click(object sender, EventArgs e)
{
string szFileName = @"c:\filename.txt";
int result = test(ticketName);
Debug.WriteLine("test=" + result);
}
|
CallingConvention = CallingConvention.Cdecl and [MarshalAs(UnmanagedType.LPWStr)] are the important parts.
The other way around, receiving a string from c++: take it as IntPtr and do this.
1
2
3
4
| IntPtr ptr = test("111111");
string data = Marshal.PtrToStringAnsi(ptr);
// 꼭 해제 한다
Marshal.FreeHGlobal(data);
|