从C DLL接收Char **到C#String []

Receive char ** from a C++ DLL into C# string[]

本文关键字:C#String Char DLL 接收      更新时间:2023-10-16

尽管有所有问题,但我找不到合适的答案。

我的目标是使用返回char** 的DLL填充string[]

dll声明

extern "C" SHTSDK_EXPORT int GetPeerList(SHTSDK::Camera *camera, int* id, int id_size, char** name, int name_size, int* statut, int statut_size);

我的导入

[DllImport(libName)]
static public extern int GetPeerList(IntPtr camera, IntPtr id, int id_size, IntPtr name, int name_size, IntPtr statut, int statut_size);

我在C#代码中的用途:

StringBuilder[] name = new StringBuilder[nbPeer];
for (int i = 0; i < nbPeer; i++)
{
     name[i] = new StringBuilder(256);
}
//Alloc peer name array
GCHandle nameHandle = GCHandle.Alloc(name, GCHandleType.Pinned);
IntPtr pointeurName = nameHandle.AddrOfPinnedObject();
int notNewConnection = APIServices.GetPeerList(cameraStreaming, pointeurId, 
nbPeer, pointeurName, nbPeer, pointeurStatut, nbPeer);
// Now I'm supposed to read string with name[i] but it crashes

我想念什么?我真的在其他主题上搜索,我认为这可以工作,但仍然崩溃。

谢谢。

我建议您开发一个小型 C /Cli bridging 层。此C /CLI桥的目的是将DLL返回的字符串数组以char** RAW POINTERS的形式,然后将其转换为.NET字符串数组,可以在您的C#代码中以简单的string[]。<<<<<<<<<<<<<<<<<<<<<</p>

C#string[](字符串数组)的C /CLI版本是array<String^>^,例如:

array<String^>^ managedStringArray = gcnew array<String^>(count);

您可以使用operator[](即managedStringArray[index])使用通常的语法将每个字符串分配给数组。

您可以写一些这样的代码:

// C++/CLI wrapper around your C++ native DLL
ref class YourDllWrapper
{
public:
    // Wrap the call to the function of your native C++ DLL,
    // and return the string array using the .NET managed array type
    array<String^>^ GetPeerList( /* parameters ... */ )
    {
        // C++ code that calls your DLL function, and gets
        // the string array from the DLL.
        // ...
        // Build a .NET string array and fill it with
        // the strings returned from the native DLL 
        array<String^>^ result = gcnew array<String^>(count);
        for (int i = 0; i < count; i++)
        {
            result[i] = /* i-th string from the DLL */ ;
        }
        return result;
    }
    ...
}

您可以在C /CLI数组上的Codeproject上找到这篇文章。


p.s。从本机dll返回的字符串的形式为 char -strings。另一方面,.NET字符串为 UNICODE UTF-16 字符串。因此,您需要澄清使用什么编码来表示本机字符串中的文本,并将.NET字符串转换为UTF-16。