【发布时间】:2013-01-26 14:11:54
【问题描述】:
我正在编写一些 C# 代码,它使用 DLLImport 来调用我的 C++ DLL 中的函数:
[DllImport("my.dll", EntryPoint = "#16", CallingConvention = CallingConvention.StdCall)]
private static extern void sendstring(string s);
我在 C# 中这样称呼它:
sendstring("Test1\\0test2\\0");
我的 C++ DLL 需要创建一个静态 const char XY[] = "Test1\0test2\0";从此,因为我需要它来从我的 c++ DLL 中调用另一个 DLLs 函数,如下所示:
functiontootherdll(sizeof(s),(void*)s);
所以我的 C++ 代码:
extern "C" {
void MyClass::sendstring( const char *s) {
functiontootherdll(sizeof(s),(void*)s);
}
问题:如果我像这样在我的 C++ DLL 中手动定义东西,它可以工作:
static const char Teststring[] = "Test1\0test2\0";
functiontootherdll(sizeof(Teststring),(void*)Teststring);
但是从我的 C# 文件调用它时它没有使用 const char *s(它会报告来自被调用的其他 dll 的不同错误)。 我需要知道如何将 const char *s 转换为 static const char s[] 之类的东西。
你知道我对这一切一无所知,所以非常欢迎任何帮助!
【问题讨论】:
-
C# 字符串是 UTF-8 (unicode)。字符是 ASCII。这可能是一个潜在问题吗?
-
您没有正确使用 sizeof。
s是一个指针,sizeof(s)产生指针的大小(4 或 8,取决于目标平台)。 -
你没有正确使用 sizeof。我该如何正确使用它?
-
即使我尝试在该 DLL 中手动设置:
const char *test = "Test1\0test2\0";然后调用functiontootherdll(2,(void*)test);它仍然存在同样的问题......它需要一个静态 const char XY[] = ".."某种方式,我不知道如何让我的 const char *test :/ -
为什么必须是 const?