簡體   English   中英

C# 中的 C:字符串作為參數和返回值?

[英]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.

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