本文介绍了C#返回类型问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a C# Class Library DLL that I call from Python.No matter what I do, Python thinks the return type is (int)I am using RGiesecke.DllExport to export the static functions in my DLL, here is an example of a function in my 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代码:

If I return an (int) it works very reliably in Python.Does anybody know what's going on?This is my Python code:

    import ctypes
    import sys
    from ctypes import *

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

Eoin

推荐答案

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

Yes, that is correct; as explained in the ctypes documentation, it is assumed that all functions return ints. You can override this assumption by setting the restype attribute on the foreign function. Here is an example using 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字符串的函数:

Or a for a function that returns a C string:

>>> 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环境中使用.

This method should also work in your Windows environment.

这篇关于C#返回类型问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 01:17