简体   繁体   中英

Calling a c dll from C++, C# and ruby

Hi I have a DLL with a function that I need to call. The signature is:

const char* callMethod(const char* key, const char* inParams);

If I use ruby everything works fine:

attach_function :callMethod, [:string, :string], :string

If I use C++ or C# I get stack overflow !?

C#:

[DllImport("DeviceHub.dll", CallingConvention = CallingConvention.Cdecl)]
private unsafe static extern IntPtr callMethod(
    [MarshalAs(UnmanagedType.LPArray)] byte[]  key,
    [MarshalAs(UnmanagedType.LPArray)] byte[] inParams
);

System.Text.UTF8Encoding encoding = new UTF8Encoding();
IntPtr p = callMethod(encoding.GetBytes(key), encoding.GetBytes(args)); // <- stack overflow here

c++:

extern "C"
{
typedef  DllImport const char*  (  *pICFUNC) (const char*, const char*); 
}
HINSTANCE hGetProcIDDLL = LoadLibrary(TEXT("C:\\JOAO\\Temp\\testedll\\Debug\\DeviceHub.dll"));  
FARPROC lpfnGetProcessID = GetProcAddress(HMODULE (hGetProcIDDLL),"callMethod");*      pICFUNC callMethod;
callMethod = (pICFUNC) lpfnGetProcessID;
const char * ptr = callMethod("c", "{}");

I have tried lots of variations for function calling : WINAPI, PASCAL, stdcall, fastcall,... nothing works.

The DLL has not been made by me and I have no control on it.

Can anyone help me with any suggestion!?

Make sure that the declaration in your header is enclosed in an extern "C" block:

extern "C" {

const char* callMethod(const char* key, const char* inParams);

}

See http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html#faq-32.3

This is just a idea but AFAIK this might be a issue with null-terminated strings, const char* myvar is null-terminated but a byte array isn't. Everything you need to to is to change the call to ...(String a, String b) and marshal them as LPStr .

I see no reason why you should not change your call to

[DllImport("DeviceHub.dll", CallingConvention = CallingConvention.Cdecl)]
private unsafe static extern string callMethod(
string key,
string inParams
);

You need to send pointers, not actual values/bytes to the function.
I always use this mapping when generating the type conversion for native function calls.
Same applies for the c++ code, you need create variables with the content and call the function then.

Stack Overflow Exception is an error put in microsoft languages to prevent infinite recursion, and to prevent incompatible programs from interacting with each other. If your dll method uses recursion, try rewriting it with iteration. Otherwise, do as Ove said, and try with strings. If it still doesn't work, Google for a compatible type. That's all I can say without knowing the actual method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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