gpt4 book ai didi

c# - 如何正确P/Invoke这个函数?

转载 作者:太空狗 更新时间:2023-10-30 00:34:51 25 4
gpt4 key购买 nike

如何正确P/Invoke这个函数?

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 header :

 {***************************************************************************
* 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。很奇怪。

最佳答案

你可能不想在这里使用 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);

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

关于c# - 如何正确P/Invoke这个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6410772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com