如何将const char*强制转换为静态const charXY[]
How to cast const char* to static const char XY[]?
我正在做一些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[] = "Test1 test2 ";
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");
我不知道这是否是一个智能解决方案,但至少它是一个:)
相关文章:
- 初始化类中的静态 const 数组 - C++
- 静态数据成员:它"const declaration / constexpr definition"起作用?
- c++ 是否保证标头初始化的静态 const 成员跨编译单元和库共享单个实例?
- 匿名命名空间中的const与静态const
- 内联初始化的静态 const 类成员的初始化顺序保证
- 从内部使用静态 std::string 的函数返回 const char * 是否安全?
- 我可以在类头文件中定义一个类的const静态实例吗
- 如何在 C++ 中的类之外使用 const 静态成员变量
- 当尝试使用它来初始化数组时,未识别C const静态成员
- const静态方法修改值
- 错误:ISO C++禁止在类内初始化非 const 静态成员
- 如何保证模板化结构中 const 静态成员的初始化顺序
- 为什么在 cpp 文件中定义了非 int const 静态
- 如何保证 const 静态成员初始化顺序
- c++如何在派生类中实现const静态成员
- 未在类中使用const静态变量优化出来
- 定义需要在运行时设置的const静态
- c++ const静态成员数组初始化
- 是否在类外部重新声明const静态变量
- 应该在c++头文件中初始化const静态变量吗