2009-05-20 81 views

回答

2

只要使用字符串,對於輸入參數就可以正常工作,但您可以使用MarshalAs屬性控制字符串的詳細信息。例如。

[DllImport("somedll.dll", CharSet = CharSet.Unicode)] 
static extern void Func([MarshalAs(UnmanagedType.LPWStr)] string wideString); 

至於返回char *參數,由於涉及對象所有權,所以這會更復雜一點。如果你可以改變C++ DLL,您可以使用CoTaskMemAllocate,喜歡的東西:

void OutputString(char*& output) 
{ 
    char* toCopy = "hello..."; 
    size_t bufferSize = strlen(toCopy); 
    LPVOID mem = CoTaskMemAlloc(bufferSize); 
    memcpy(mem, toCopy, bufferSize); 
    output = static_cast<char*>(mem); 
} 

的C#側然後只使用一種「串出」參數,垃圾收集器可以拿起字符串的所有權。

這樣做的另一種方法是使用StringBuilder,但是在實際調用函數之前,您需要知道字符串的大小。

3

如果參數是隻讀的,那麼字符串應該可以工作,如果方法修改了字符串,您應該使用StringBuilder來代替。從下面參考

例子:

[DllImport ("libc.so")] 
private static extern void strncpy (StringBuilder dest, 
     string src, uint n); 

private static void UseStrncpy() 
{ 
    StringBuilder sb = new StringBuilder (256); 
    strncpy (sb, "this is the source string", sb.Capacity); 
    Console.WriteLine (sb.ToString()); 
} 

如果你不知道怎麼的P/Invoke編組的作品,你可以閱讀http://www.mono-project.com/Interop_with_Native_Libraries

如果你只用繩子conserning,只讀部分:http://www.mono-project.com/Interop_with_Native_Libraries#Strings

0

不知道這個工程,但你有沒有試着用

StringObject.ToCharArray(); 

不確定從char * tho初始化字符串。 Mybe只是分配給一個字符串對象,值得一試。

0

你試過了StringBuilder嗎?我發現這在谷歌搜索:

[DllImport("advapi32.dll")] 
public static extern bool GetUserName(StringBuilder lpBuffer, ref int nSize); 

如果你發佈你正在做的電話,我們可以幫你組裝。