C# Return Type Issue

耗尽温柔 提交于 2019-12-12 18:42:46

问题


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";
}

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


回答1:


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'>

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'

This method should also work in your Windows environment.




回答2:


Just because the datatypes are given the same name doesn't mean that they are actually the same. It sounds as it python is expecting a different structure for what it calls a "float".

This previous answer may be of use, and this answer states that a python float is a c# double; so my advice would be to try returning a double from your c# code.



来源:https://stackoverflow.com/questions/34810495/c-sharp-return-type-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!