我想一個乾淨的方式增加,因爲需要通過本機代碼人口的StringBuilder()的大小,回調方法如下似乎乾淨,但不知何故我們得到了一個緩衝區的副本,而不是實際的緩衝區 - 我對解釋和解決方案感興趣(最好堅持回調類型分配,因爲如果只有它可以工作,它會很好,很乾淨)。我怎樣才能返回一個StringBuilder或其他字符串緩衝區從PInvoke的本地回調
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace csharpapp
{
internal class Program
{
private static void Main(string[] args)
{
var buffer = new StringBuilder(12);
// straightforward, we can write to the buffer but unfortunately
// cannot adjust its size to whatever is required
Native.works(buffer, buffer.Capacity);
Console.WriteLine(buffer);
// try to allocate the size of the buffer in a callback - but now
// it seems only a copy of the buffer is passed to native code
Native.foo(size =>
{
buffer.Capacity = size;
buffer.Replace("works", "callback");
return buffer;
});
string s = buffer.ToString();
Console.WriteLine(s);
}
}
internal class Native
{
public delegate StringBuilder AllocateBufferDelegate(int bufsize);
[DllImport("w32.dll", CharSet = CharSet.Ansi)]
public static extern long foo(AllocateBufferDelegate callback);
[DllImport("w32.dll", CharSet = CharSet.Ansi)]
public static extern void works(StringBuilder buf, int bufsize);
}
}
本地頭
#ifdef W32_EXPORTS
#define W32_API __declspec(dllexport)
#else
#define W32_API __declspec(dllimport)
#endif
typedef char*(__stdcall *FnAllocStringBuilder)(int);
extern "C" W32_API long foo(FnAllocStringBuilder fpAllocate);
extern "C" W32_API void works(char *buf, int bufsize);
本地代碼
#include "stdafx.h"
#include "w32.h"
#include <stdlib.h>
extern "C" W32_API long foo(FnAllocStringBuilder fpAllocate)
{
char *src = "foo X";
int len = strlen(src) + 1;
char *buf = fpAllocate(len);
return strcpy_s(buf,len,src);
}
extern "C" W32_API void works(char *buf, int bufsize)
{
strcpy_s(buf,bufsize,"works");
}
嘗試標誌着'StringBuilder'參數作爲'[輸入,輸出]'在P /調用簽名。 – Polynomial 2012-02-21 13:46:46
作爲參數傳遞的StringBuilder工作正常 - 它是從函數指針/委託返回的一個問題。 – dice 2012-02-21 13:50:24
有點令人驚訝的是,返回的'StringBuffer'顯然與傳入的參數不同。這可能只是它的方式,你必須解決它。 +1雖然。 – 2012-02-21 15:26:07