2017-08-31 33 views
2

すべての質問にもかかわらず、これを行うには適切な答えが見つかりません。C++のDLLからC#の文字列を受け取る[]

私の目標はです。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 

Whを私は逃した?私は実際に他のトピックを検索しましたが、私はthis oneがうまくいくと思っていましたが、まだクラッシュしていました。

ありがとうございました。

+1

私は混合アセンブリ(cliサポート付きビジュアル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から返された文字列配列を取得し、単純なstring[]としてC#コードで使用できる.NET文字列配列に変換することです。

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でthis article on CodeProjectを見つけることができ、同様に興味深い読書をするアレイ。


P.S.ネイティブDLLから返される文字列は、char -stringsの形式です。一方、.NET文字列はUnicode UTF-16文字列です。したがって、ネイティブ文字列内のテキストを表現するために使用されるエンコーディングと、.NET文字列のためのUTF-16に変換されるエンコーディングを明確にする必要があります。

関連する問題