gpt4 book ai didi

c++ - Marshall char** to string 从托管代码调用非托管代码的问题

转载 作者:太空宇宙 更新时间:2023-11-04 12:19:03 24 4
gpt4 key购买 nike

我有这个 C++ 函数,

    bool MyClass::my_function(int num, TCHAR** filepath)

我已经将函数公开为

    extern "C"
{
__declspec(dllexport) bool MyFunction(int num, char* filepath[])
{
OutputDebugStringA("--MyFunction--");
TCHAR **w_filepath = (TCHAR **)calloc(num, 2* sizeof(TCHAR **));
for(int i = 0; i < num; i++)
{
OutputDebugStringA(filepath[i]);
int len = strlen(filepath[i]) + 1;
w_filepath[i] = (TCHAR *)calloc (1, len);
ctow(w_filepath[i], filepath[i]); // converts char to WCHAR
}

bool ret = MyClass.my_function(num, w_filepath);
OutputDebugStringA("End -- MyFunction --");
free(w_filepath);
return ret;
}
}

我有 C# 包装器作为

    [DllImport("MyDll.dll")]
public static extern bool MyFunction(int num, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPTStr)] string[] filepath);

在 C# 中,我将 Myfunction 称为

    string [] filepath = { "D:\\samplefile\\abc.txt", "D:\\samplefile\\def.txt"}
MyFunction(2, filepath)

在 C++ 函数中,它只获取文件路径的第一个字符。例如,如果我使用

在 C++ 代码中打印,则从上面的调用
    OutputDebugStringA

它只为第一个和第二个打印 D。

如果我删除

    [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPTStr)]

来自 c# 包装器我将在

中收到访问冲突错误
    w_filepath[i] = (TCHAR *)calloc (1, len) 

第二个文件。

请帮帮我。

最佳答案

1) w_filepath[i] = (TCHAR *)calloc (1, len); - calloc 需要以字节为单位的大小,所以它应该是 w_filepath[i] = (wchar_t * )calloc (1, len*sizeof(wchar_t));

2) 来自c#的数据以wchar_t*形式出现,所以你根本不需要转换例程,并且应该将函数声明更改为

__declspec(dllexport) bool MyFunction(int num, wchar_t* filepath[])

关于c++ - Marshall char** to string 从托管代码调用非托管代码的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6069185/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com