将C#字符串作为参数发送到非托管C ++ DLL函数 [英] Sending a C# string as an argument to a unmanaged C++ DLL function

查看:480
本文介绍了将C#字符串作为参数发送到非托管C ++ DLL函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的C#字符串发送到C ++ DLL函数。我已经成功,都与StringBuilder:

I want to send my C# string to a C++ DLL function. I have succeeded, both with StringBuilder:

[C#]
public static extern int installHook(StringBuilder directory);
StringBuilder myText = new StringBuilder(512);
myfunc(myText);

[C++]
int OPENGLHOOK_API myfunc(char* directory)
{
    ::MessageBoxA(NULL,directory,"test123",0);
}

wchar:

[C#]
public static extern int installHook(string directory);
myfunc("myText");

[C++]
int OPENGLHOOK_API installHook(wchar* directory)
{
    wstring s = directory;
    const wchar_t* wstr = s.c_str();
    size_t wlen = wcslen(wstr) + 1;
    char newchar[100];
    size_t convertedChars = 0;
    wcstombs_s(&convertedChars, newchar, wlen, wstr, _TRUNCATE);

    ::MessageBoxA(NULL,newchar,"test123",0);
}

,因为它在StackOverflow上的其他线程中提到。问题是,每次我这样做,我得到一个错误,因为函数签名是不一样的:

as it was mentioned in other thread on StackOverflow. The problem is that everytime I do this, I get an error because the function signatures are not the same:

托管调试助手'PInvokeStackImbalance'检测到'C :\Users\Dave\Documents\Visual Studio 2010\Projects\OpenGLInjector\Loader\bin\Release\Loader.vshost.exe'。
附加信息:调用PInvoke函数'Loader!Loader.Form1 :: myfunc'使堆栈不平衡。这很可能是因为托管PInvoke签名与非托管目标签名不匹配。检查PInvoke签名的调用约定和参数是否匹配目标非托管签名。

Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem in 'C:\Users\Dave\Documents\Visual Studio 2010\Projects\OpenGLInjector\Loader\bin\Release\Loader.vshost.exe'. Additional Information: A call to PInvoke function 'Loader!Loader.Form1::myfunc' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

任何想法如何解决我的问题/从这里做什么?

Any idea how I can fix my problem/what to do from here?

推荐答案

我相信问题是两种语言之间的默认调用约定。 C#是 __ stdcall 和c ++是 __ cdecl ,我相信。尝试在您的C ++方法签名上明确指出 __ stdcall ,看看是否不能解决错误。

I believe the problem is the default calling convention between the two languages. C# is __stdcall and c++ is __cdecl, I believe. Try explicitly stating __stdcall on your C++ method signatures and see if that doesn't resolve the error.

C ++:

int OPENGLHOOK_API __stdcall installHook(wchar* directory)

C#:

[DllImport( "yourdll.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode )]
static extern int installHook(string directory);

这篇关于将C#字符串作为参数发送到非托管C ++ DLL函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆