When I write an int64 type number to the function, a different number is returned

Question:

I converted the golang code to c code and called it from python. but when the function should return a number close to the number I wrote inside, it returns a very different number.

main.py

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)

returning number: 705032703

golang code that I converted to c code

main.go

package main

import "C"

func helloWorld(x int64) int64 {
    s := int64(1)
    for i := int64(1); i < x; i++ {
        s = i
    }
    return s
 }
Asked By: can

||

Answers:

You’re making the mistake 99% of new ctypes users: not declaring the argument types and return type of the function used. ctypes assumes c_int for scalars and c_void_p for pointers on arguments and c_int for return type unless told otherwise. If you define them, you don’t have to wrap every parameter in the type you want to pass, because ctypes will already know.

I’m not set up for Go, but here’s a simple C implementation of the function with a 64-bit argument and return type:

#include <stdint.h>

#ifdef _WIN32
#   define API __declspec(dllexport)
#else
#   define API
#endif

API int64_t helloWorld(int64_t x) {
        return x + 1;
}

The Python code to call it:

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
Answered By: Mark Tolonen
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.