gpt4 book ai didi

c# - 调用 native 函数时最后一个参数出现损坏

转载 作者:行者123 更新时间:2023-11-30 15:44:44 24 4
gpt4 key购买 nike

正在为 native (C) 库开发 C# 包装器。我在 native 库中有以下函数原型(prototype):

typedef struct _NativeObj *       NativeObj;
typedef struct AnotherNativeObj * AnotherNative;

__declspec(dllimport) NativeObj createNativeObj (
AnotherNative * anotherNative,
FirstCallback firstCallback,
void * firstOpaque,
SecondCallback secondCallback,
void * secondOpaque,
ThirdCallback thirdCallback,
void * thirdOpaque,
const char * firstString,
const char * secondString,
const char * thirdString,
time_t timeout,
char * fourthString,
int firstInt,
int secondInt,
int thirdInt,
int fourthInt,
char * fifthString,
int fifthInt,
char * sixthString);

这是 C# 代码中的声明:

public delegate int ThirdCallbackDelegate(...);

public const uint NO_TIMEOUT = 0;

private uint timeout = NO_TIMEOUT;
private string fourthString;
private uint firstInt = 0;
private bool secondInt = false;
private bool thirdInt = true;
private bool fourthInt = true;
private string fifthString;
private bool fifthInt = false;
public string sixthString { get; set; }

[DllImport("path\\to.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr createNativeObj(
IntPtr anotherNative,
FirstCallbackDelegate firstCallback,
IntPtr firstOpaque,
SecondCallbackDelegate secondCallback,
IntPtr secondOpaque,
ThirdCallbackDelegate thirdCallback,
IntPtr thirdOpaque,
string firstString,
string secondString,
string thirdString,
int timeout,
string fourthString,
int firstInt,
int secondInt,
int thirdInt,
int fourthInt,
string fifthString,
int fifthInt,
string sixthString);

参数背后的逻辑:

IntPtr myOpaque = createNativeObj(IntPtr.Zero,
null,
IntPtr.Zero,
null,
IntPtr.Zero,
thirdCallbackDelegate,
IntPtr.Zero,
firstString,
secondString,
thirdString,
(int)timeout,
fourthString,
(int)firstInt,
Convert.ToInt32(secondInt),
Convert.ToInt32(thirdInt),
Convert.ToInt32(fourthInt),
fifthString,
Convert.ToInt32(fifthInt),
sixthString);

在运行时,就在 native 函数开始时,超时后参数的值被损坏。

最佳答案

在 Windows 上,使用 MS 工具,并假设您未定义 _USE_32BIT_TIME_T,则 time_t 类型为 8 字节宽。这意味着您需要在 C# p/invoke 代码中将其声明为 long 才能匹配。

关于c# - 调用 native 函数时最后一个参数出现损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19344851/

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