开发者

Problem with Marshalling char* in c#

I have a problem calling this function from a c++ DLL in c#

INT32 WINAPI PM_COM_GetText(INT32 TextId, char* pBuf, INT32 BufSize);

It writes a Text in a buffer for a given text id. I try to call it with the following c# code, but I constantly get an access violation and don't undrestand why:

public string GetText(Int32 TextId)
{
  Int32 BufSize = 256;
  StringBuilder Str = new StringBuilder(BufSize);
  PM_COM_GetText(TextId, Str, BufSize);
  return Str.ToString();
}

[DllImport("ComDll.dll", CharSet = CharSet.Ansi)]
private static extern Int32 PM_COM_GetText(Int32 TextId, StringBuilder Str, Int32 BufSize);

I don't see what's wrong, it looks to me 开发者_如何学Golike many other code snippets I found in the web.

Any ideas? Thanks in advance!


The StringBuilder Str in the DllImport declaration looks strange to me. I'd suggest trying to make it a plain ol' string.


Yep, string builder looks strange. Maybe char[]??? You should also check if actually those are not uints.

These kind if things (using int when you should use uint, lets say) will have no problem in C++ but will throw an exception in .net 2


Maybe try using out StringBuilder Str or out string Str


Try making the StringBuilder parameter a byte[] and use

Encoding.UTF8.GetBytes("yourstring")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜