如何从 clr 程序集中返回 char* 数组?
我有一个简单的托管 C++ 程序集,我为 C# 程序集中的一些静态方法提供非托管包装器。其中一种方法返回一个字符串,我已将其转换为 C++ 程序集中的“const char*”类型。我遇到的问题是,当我从非托管源加载这个 dll 时,我在指针中得到了错误的数据。对此我能做什么?我已将我的测试用例简化为:
托管程序集(使用 /clr 编译的 Test.dll;完整代码如下):
extern "C" {
__declspec(dllexport) const char* GetValue(const char* s) {
return s;
}
}
非托管控制台 win32 应用程序:
#include "stdafx.h"
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
typedef const char* (*GetValueFunc)(const char* s);
int _tmain(int argc, _TCHAR* argv[]) {
wprintf(L"Hello from unmanaged code\n");
HMODULE hDll = LoadLibrary(L"Test.dll");
if (!hDll)
return GetLastError();
wprintf(L"library found and loaded\n");
GetValueFunc getValue = (GetValueFunc)GetProcAddress(hDll, "GetValue");
if(!getValue)
return GetLastError();
wprintf(L"%s\n", getValue("asdf"));
return 0;
}
我得到前两行很好,但出现的第三行是垃圾。我是否让 dll 在 cpp 文件顶部具有“#pragma unmanaged”也并不重要(相同的结果)。
I have a simple managed C++ assembly which I am providing unmanaged wrappers for some static methods I have in a C# assembly. One of these methods returns a string which I have converted to a "const char*" type in the C++ assembly. The trouble I am having is that when I load this dll from an unmanaged source, I get bad data back in the pointer. What can I do about this? I have simplified my testcase down to this:
managed assembly (Test.dll compiled with /clr; full code follows):
extern "C" {
__declspec(dllexport) const char* GetValue(const char* s) {
return s;
}
}
unmanaged console win32 app:
#include "stdafx.h"
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
typedef const char* (*GetValueFunc)(const char* s);
int _tmain(int argc, _TCHAR* argv[]) {
wprintf(L"Hello from unmanaged code\n");
HMODULE hDll = LoadLibrary(L"Test.dll");
if (!hDll)
return GetLastError();
wprintf(L"library found and loaded\n");
GetValueFunc getValue = (GetValueFunc)GetProcAddress(hDll, "GetValue");
if(!getValue)
return GetLastError();
wprintf(L"%s\n", getValue("asdf"));
return 0;
}
I get the first two lines just fine, but the third line that comes out is garbage. It also doesn't matter if I make the dll have "#pragma unmanaged" at the top of the cpp file or not (same results).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
带有 %s 格式说明符的 wprintf 会将您的第一个参数解释为“const wchar_t*”,同时您将“const char*”传递给它。尝试在 GetValue 函数中使用 wchar_t 。
wprintf with a %s format specifier will interpret your first parameter as a "const wchar_t*", while you're passing a "const char*" to it. Try to use wchar_t in your GetValue function.