【问题标题】:How to cast const char* to static const char XY[]?如何将 const char* 转换为静态 const char XY[]?
【发布时间】: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?

标签: c++ arrays char constants


【解决方案1】:

好吧,我找到了一种我认为的方法:

我将 C++ 修改为:

extern "C" {
void MyClass::sendstring( const char *s) {
int le = strlen(s);
char p[256];
strcpy(p,s);
char XY[sizeof(p) / sizeof(*p) + 1];
int o=0;
for (int i = 0; i<le;i++) {     
    if (p[i] == ';') {
        XY[i] = '\0';
    } else {
    XY[i] = p[i];
    }
    o++;
}
XY[o] = '\0';
functiontootherdll(sizeof(XY),(void*)XY);
}

之后函数调用

functiontootherdll(sizeof(XY),(void*)XY);

工作正常。

请注意,我现在从我的 C# 代码中发送了一个类似“Test1;test2;test3;...”的字符串,尝试使用 \\0 作为分隔符没有成功。我对 C# 的调用是:

sendstring("Test1;test2;test3");

我不知道这是否是一个聪明的解决方案,但至少它是一个:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多