gpt4 book ai didi

C# 返回类型问题

转载 作者:行者123 更新时间:2023-11-30 21:52:22 25 4
gpt4 key购买 nike

我有一个从 Python 调用的 C# 类库 DLL。无论我做什么,Python 都认为返回类型是 (int)我正在使用 RGiesecke.DllExport 导出我的 DLL 中的静态函数,这是我的 C# DLL 中的函数示例:

[DllExport("Test", CallingConvention = CallingConvention.Cdecl)]   
public static float Test()
{

return (float)1.234;
}

[DllExport("Test1", CallingConvention = CallingConvention.Cdecl)]
public static string Test1()
{

return "123456789";
}

如果我返回一个 (int) 它在 Python 中工作非常可靠。有人知道发生了什么事吗?这是我的 Python 代码:

    import ctypes
import sys
from ctypes import *

self.driver = ctypes.cdll.LoadLibrary(self.DLL)
a= self.driver.Test()

伊币

最佳答案

是的,这是正确的;如 ctypes documentation 中所述,假定所有函数都返回 int。您可以通过在外部函数上设置 restype 属性来覆盖此假设。这是一个使用 libc (linux) 的示例:

>>> import ctypes
>>> libc = ctypes.cdll.LoadLibrary("libc.so.6")
>>> libc.strtof
<_FuncPtr object at 0x7fe20504dd50>
>>> libc.strtof('1.234', None)
1962934
>>> libc.strtof.restype = ctypes.c_float
>>> libc.strtof('1.234', None)
1.2339999675750732
>>> type(libc.strtof('1.234', None))
<type 'float'>

或者对于返回 C 字符串的函数:

>>> libc.strfry
<_FuncPtr object at 0x7f2a66f68050>
>>> libc.strfry('hello')
1727819364
>>> libc.strfry.restype = ctypes.c_char_p
>>> libc.strfry('hello')
'llheo'
>>> libc.strfry('hello')
'leohl'
>>> libc.strfry('hello')
'olehl'

此方法也适用于您的 Windows 环境。

关于C# 返回类型问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34810495/

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