[英]C from C#: string as parameter and return value?
我在 Win32 DLL 的.c
文件中調用doThis
函數。
#include <stdio.h>
__declspec(dllexport) double doThis( char *message)
{
printf("do nothing much");
return 32.5;
}
使用此調用代碼:
[DllImport(@"\\vmware-host\Shared Folders\c-sharp\Hot\MusicIO\Debug\HelloWorld.dll",
CallingConvention=CallingConvention.Cdecl)]
public static extern double doThis(string message);
private void button1_Click(object sender, EventArgs e)
{
double returned = doThis("what 2");
MessageBox.Show("Click " + returned);
}
這工作正常,但我希望函數返回一個char *
... 並返回message
變量。
當我更改doThis
以返回一個char *
並且調用代碼期望一個string
,Win32 Host 在運行時崩潰。
有什么建議嗎?
[奇怪的是,我想我之前有過這個工作]
讓我們假設有一段時間這個簽名有效:
__declspec(dllexport) char* doThis(char* message)
你從 C# 調用它,然后你有一個char*
。 你將它復制到一個string
,然后......然后呢? 你用那個char*
做什么?
你free
打電話嗎? 順便說一下, free
的哪個C 運行時庫? 或者也許你不應該因為指針可能來自靜態內存? 你不知道,.NET mashaller 也不知道。
處理此問題的正確方法是傳遞第二個char*
參數,該參數指向您分配的某個緩沖區,並且您負責釋放。
嗯,在 C# 中,這並不一定是你。 編組員可以為您處理。
所以定義一個這樣的簽名:
__declspec(dllexport) double doThis(char* message, char* output, int maxOutputLength)
maxOutputLength
參數是一種安全措施,讓您的 C 代碼知道消息的最大長度。 在您的 C 代碼中按照您認為合適的方式使用它。
注意:在 C++ 代碼中, message
將是一個const char*
,而output
將保持一個char*
。
在 C# 方面,簽名將涉及StringBuilder
:
[DllImport(@"HelloWorld.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern double doThis(string message, StringBuilder output, int maxOutputLength);
然后,您分配一個具有一些初始容量的StringBuilder
,並將其傳遞給:
var output = new StringBuilder(1024);
double returned = doThis("what 2", output, output.Capacity);
var outputStr = output.ToString();
編組員會為您處理管道。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.