2017-09-15 2 views
0

以下は、c#とC++/dllの間の文字列型のマーシャリングをよりよく理解するためのおもちゃの例です。dllからcへのstrncpy関数の整列#

以下の「MyStrCopy」機能をc#にマーシャリングする最も良い方法は何ですか? (好ましくは安全でないキーワードを使用しないとに、文字列型としてのC#のうちの種類をマーシャリングすることによって。)

ファイル:MyStrCopy.cs

using System.Runtime.InteropServices; 

namespace MySpace { 
    class MyDll { 
     [DllImport (@"MyStrCopy")] 
     public static extern void MyStrCopy(
      string dest????, string source????, int dest_length????); 
    } 
} 

FILE:MyStrCopy.h:

extern "C" { 
    void __declspec(dllexport) MyStrCopy(
     char* dest, const char* source, int dest_length); 
} 

FILE:MyStrCopy.cpp

#include <cstring> 
#include "MyStrCopy.h" 

void MyStrCopy(char* dest, const char* source, int dest_len) { 
    strncpy(dest, source, dest_len); 
    dest[dest_len-1] = 0; // zero terminated when source > dest 
} 

は、私は上記のファイルをコンパイル「MyStrCopy.cp p "を呼び出すMyStrCopy.dll

文字列に安全でないマーシャリングタイプを使用しないという同じ設定の下でchar *を返すと、少し奇妙に思えます。例では、DLLがエクスポートされた場合、関数ではなく、次のようになります。それは、ゼロ終了します保証するものではありませんので、デザインによって破壊されたC関数を使用して

char* MyStrCopy(char* dest, const char* source, int dest_len) { 
    return strncpy(dest, source, dest_len); 
} 
+0

は非常に賢明ではありません、strncpyを()致命的な欠陥があります文字列これにより、C#プログラムが検出不能なAccessViolationExceptionでクラッシュします。このおもちゃは、もう一つのプログラマーの大きな頭痛で、閉幕することになるだろう。 –

+0

これは良い点です。strncpy()の後に次の行を追加すると、すべての場合に動作します。dest [dest_len-1] = 0;とにかく、要点はC#の[DllImport]構文の例です。strncpy()のような関数に文字列を渡すことができます。私の場合は、実際にはDLLの相互運用を使用して、C++側からC#側にリストを追加します。 –

答えて

1
using System.Text; 
using System.Runtime.InteropServices; 

namespace MySpace 
{  
    class MyDll { 
     [DllImport("MyStrCopy.dll", CharSet = CharSet.Ansi)] 
     public static extern void MyStrCopy(
      StringBuilder dst_str, 
      string   src_str, 
      int   dst_len);  

     static void ExampleUsage() { 
      int   dest_len = 100; 
      StringBuilder dest_str = new StringBuilder(dest_len); 
      string  source  = "this is a string"; 
      MyStrCopy(dest_str, source, dest_len); 
      return; 
     }  

    } //class 
} //namespace 
関連する問題