簡體   English   中英

如何通過P / Invoke封送cstring *?

[英]How do I marshal cstring* via P/Invoke?

我試圖從C#調用第三方DLL,但無法整理一些字符串數據。 DLL是用Clarion編寫的,我對所使用的數據類型不是很熟悉。 具體來說,該規范具有我無法使用的功能的以下簽名:

Bool QuerySoftwareVersion( cstring* version)  // edited documentation typo
//Returns Software version (20 character cstring).  

我以為cstring只是一個以空字符結尾的字符串,但是在我的定義中,我無法使它與out char[] version一起使用。 有人知道正確的處理方式嗎?

編輯:實際上,到目前為止,我發現這表明Clarion中的cstring確實只是一個以空字符結尾的字符串。

更新:我已經更新了問題的標題和詳細信息,因為事實證明DLL文檔中有錯字。 有問題的version參數聲明為cstring*類型,而不是cstringt*. And in Clarion,類型cstringt*. And in Clarion, cstringt*. And in Clarion, cstring`顯然只是一個c樣式,以null終止的字符串。 因此,封送處理不應該那么復雜,因為他們聲稱封送處理是使用C調用約定編寫的。 有沒有人成功地p /調用了通過參考參數傳遞字符串的Clarion DLL?

我從未調用過Clarion,但是我有一個Clarion和C#都調用過的DLL(用C語言編寫),我將其互操作為:

[DllImport("clarionlib.dll", CharSet=CharSet.Ansi,
CallingConvention = CallingConvention.Cdecl,
ExactSpelling=true, EntryPoint="QuerySoftwareVersion")] static extern
            bool QuerySoftwareVersion(StringBuilder sName);

還要注意,您傳遞的StringBuilder參數的大小必須達到最大預期返回值的大小(請原諒我的C#,我敢肯定等效項會更短):

System.Text.StringBuilder buffer;
buffer = new System.Text.StringBuilder();
buffer.EnsureCapacity(21);
QuerySoftwareVersion(buffer);
string myString = buffer.ToString();

我在DLL API中使用CString引用取得了一些成功:

SCODE WINAPI Test( const CString& str );

我使用以下C#代碼導入:

[DllImport("CBData.Dll")]
public static extern int Test( [MarshalAs(UnmanagedType.LPStr)] ref String str );

並調用以下C#代碼:

String b = "Some text";
int x = Test(ref b);

這對我有用-我不確定這是否安全。 我希望這可以幫助你。

嘗試使用StringBuilder:

[DllImport("mylibrary.dll")]
static extern bool QuerySoftwareVersion([Out] StringBuilder version);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM