2017-08-31 59 views
2

尽管存在所有问题,但我找不到合适的答案。将char **从C++ DLL接收到C#string []

我的目标是填充一个string[]配合使用,它返回一个char**一个DLL的。

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 

瓦我错过了吗?我真的搜索了其他主题,我认为this one可以工作,但仍然崩溃。

谢谢。

+1

我会建议做一个混合程序集(带有cli支持的visual C++),并将其用作本机(C++)函数的包装。这比你现在做的要容易得多。 –

+0

也许它可能有帮助吗? https://stackoverflow.com/questions/11508260/passing-stringbuilder-to-dll-function-expecting-char-pointer#11509815 – R2RT

回答

0

我建议你开发一个小巧的C++/CLI桥接层。此C++/CLI桥接器的目的是以char**原始指针的形式获取由DLL返回的字符串数组,并将其转换为.NET字符串数组,该数组可作为简单的string[]在C#代码中使用。

的C++/CLI版本C#string[](字符串数组)的是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 this article on CodeProject ++/CLI数组一个有趣的阅读也是如此。


P.S.从本地DLL返回的字符串的形式为char -strings。另一方面,.NET字符串是Unicode UTF-16字符串。因此,您需要阐明用什么编码来表示本地字符串中的文本,并将其转换为用于.NET字符串的UTF-16。