[英]When I write an int64 type number to the function, a different number is returned
我将 golang 代码转换为 c 代码并从 python 调用它。 但是当 function 应该返回一个接近我在里面写的数字的数字时,它返回一个非常不同的数字。
主文件
import ctypes
library = ctypes.cdll.LoadLibrary('./maintain.so')
hello_world = library.helloWorld
numb = 5000000000
n = ctypes.c_int64(numb)
x = hello_world(n)
print(x)
退货号码:705032703
我转换为 c 代码的 golang 代码
主.go
package main
import "C"
func helloWorld(x int64) int64 {
s := int64(1)
for i := int64(1); i < x; i++ {
s = i
}
return s
}
99% 的新ctypes
用户都犯了错误:没有声明使用的 function 的参数类型和返回类型。 ctypes
假定c_int
用于标量, c_void_p
用于 arguments 上的指针, c_int
用于返回类型,除非另有说明。 如果定义它们,则不必将每个参数都包装在要传递的类型中,因为ctypes
已经知道了。
我没有为 Go 设置,但这里有一个简单的 C 实现,带有 64 位参数和返回类型:
#include <stdint.h>
#ifdef _WIN32
# define API __declspec(dllexport)
#else
# define API
#endif
API int64_t helloWorld(int64_t x) {
return x + 1;
}
调用它的 Python 代码:
import ctypes as ct
dll = ct.CDLL('./test')
dll.helloWorld.argtypes = ct.c_int64, # sequence of argument types
dll.helloWorld.restype = ct.c_int64 # return type
# Note you don't have to wrap the argument, e.g. c_int64(5000000000).
print(dll.helloWorld(5_000_000_000))
Output:
5000000001
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.