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

Pom*_*oma 4 c# pinvoke

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

const char * GetReplyTo(const char * pszInText, char * pszOutText, int len)
Run Code Online (Sandbox Code Playgroud)

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

[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);
Run Code Online (Sandbox Code Playgroud)

UPDATE 这是此文件的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.
Run Code Online (Sandbox Code Playgroud)

更新2它的工作原理.看起来我搞砸了初始化功能.成功时返回1,失败时返回0.奇怪的.

Joe*_*ite 5

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

[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);
Run Code Online (Sandbox Code Playgroud)

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