如何正确P /调用此功能?

时间:2011-06-20 11:59:43

标签: c# pinvoke

如何正确P /调用此功能?

const char * GetReplyTo(const char * pszInText, char * pszOutText, int len)

我试过这样做并且获得了访问冲突异常:

[DllImport("SmartBot.dll", EntryPoint = "GetReplyTo")]
public static extern IntPtr GetReplyTo([In] [MarshalAs(UnmanagedType.LPStr)] string pszInText, IntPtr pszOutText, int len);

// somewhere below:
IntPtr pbuf = GCHandle.Alloc(new byte[1000], GCHandleType.Pinned).AddrOfPinnedObject();
GetReplyTo("hi", pbuf, 2);

更新 这是此文件的pascal标题:

 {***************************************************************************
 * SmartBot Engine - Boltun source code,
 * SmartBot Engine Dynamic Link Library
 *
 * Copyright (c) 2003 ProVirus,
 * Created Alexander Kiselev Voronezh, Russia
 ***************************************************************************
 SmartBot.pas : Header Pascal for SmartBot Engine.
 }

unit SmartBot;

interface

{
function GetReplyTo(const InText: PChar; OutText: PChar; Len: integer): PChar;stdcall;export;
function LoadMind(MindFile: PChar): integer;stdcall;export;
function SaveMind(MindFile: PChar): integer;stdcall;export;
}
function GetReplyTo(const InText: PChar; OutText: PChar; Len: integer): PChar;stdcall;external 'smartbot.dll' name 'GetReplyTo';
function LoadMind(MindFile: PChar): integer;stdcall;external 'smartbot.dll' name 'LoadMind';
function SaveMind(MindFile: PChar): integer;stdcall;external 'smartbot.dll' name 'SaveMind';

implementation
end.

更新2 它有效。看起来我搞砸了初始化功能。成功时返回1,失败时返回0。怪异。

2 个答案:

答案 0 :(得分:5)

您可能不希望在此IntPtr。你为自己做了太多的工作。对于输出字符串参数,您应该使用StringBuilder。您可能需要在P / Invoke声明中指定CharSet,因为该函数似乎每个字符使用一个字节。

[DllImport("SmartBot.dll", CharSet = CharSet.Ansi)]
public static extern string GetReplyTo(string pszInText,
    StringBuilder pszOutText, int len);

var stringBuilder = new StringBuilder(1000);
GetReplyTo("hi", stringBuilder, stringBuilder.Capacity);

还要确保您指定了正确的调用约定(CallingConvention属性上的DllImport属性)。

答案 1 :(得分:3)

您应该将StringBuilder用于初始化为len

的第二个参数
相关问题