如何将const char*强制转换为静态const charXY[]

How to cast const char* to static const char XY[]?

本文关键字:const 静态 charXY 转换 char      更新时间:2023-10-16

我正在做一些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需要创建一个静态常量字符XY[]="Test1\0test2\0";从这个开始,因为我需要它来从我的c++DLL内部调用另一个DLL函数,如下所示:

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[] = "Test1test2";
functiontootherdll(sizeof(Teststring),(void*)Teststring);

但当从我的C#文件调用它时,它没有使用const char*s(它将报告与被调用的其他dll不同的错误)。我需要知道如何将const char*s转换为类似静态const chars[]之类的类型。

正如你所意识到的,我对这一切一无所知,所以任何帮助都是非常欢迎的!

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

我将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] = '';
    } else {
    XY[i] = p[i];
    }
    o++;
}
XY[o] = '';
functiontootherdll(sizeof(XY),(void*)XY);
}

之后对的函数调用

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

运行良好。

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

sendstring("Test1;test2;test3");

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