Friday, January 30, 2015

Call C++ Functions in a DLL using C#

P/Invoke is an efficient method for calling native code functions in an unmanaged DLL. The below code samples show the source code a native code library which defines a very simple C++ function which accepts a char* argument.
MyLib.h
__declspec(dllexport) int Hello(char* pszBuffer, int nLengthObj);
MyLib.cpp
#include “stdafx.h”
#include “MyLib.h”
#include
__declspec(dllexport) int SayHello(char* pszBuffer, int nLengthObj)
{
::strcpy_s(pszBuffer, nLength, “Hello, from the C++ DLL”);
return strlen(pszBuffer);
}
LIBRARY “MyLib”
EXPORTS
Hello
From C#, calling this function is relatively simple. The below code shows this as well as when calling a method that takes char* you first need to convert the string to bytes.
[DllImport(“MyLib.dll”, ExactSpelling=false,
CallingConvention=CallingConvention.Cdecl, EntryPoint=”Hello”)]
public static extern int Hello(
[MarshalAs(UnmanagedType.LPArray)] byte[] buffer,int length);
static void Main(string[] args)
{
int size = 32;
//we need to manually marshal the bytes to a String
byte[] buffer = new byte[size];
int returnVal = Hello(buffer, size);
string result = Encoding.ASCII.GetString(buffer,0, returnVal);
Console.WriteLine(“”{0}”, return value: {1}”, result, returnVal);
}

No comments:

Post a Comment