How to pass a GMP mpf_t from C++ to Python with ctypes?

34 views Asked by At

I have some C++ code that calculates a result as a GMP mpf_t value. I need to access that value in Python, but I can't seem to find any way of passing it with ctypes.

One of my many, many failed attempts is below...

foo.cpp:

#include <gmp.h>

extern "C" mpf_t* create_number(double d)
{   
    mpf_t* x;
    mpf_init_set_d(*x, d);
    
    return x;
}

bar.py:

import ctypes
import gmpy2

lib = ctypes.CDLL('foo.so')

# Define function prototype
create_number = lib.create_number
create_number.argtypes = [ctypes.c_double]
create_number.restype = ctypes.POINTER(ctypes.c_void_p)  # I want gmpy2.mpfr!!

mpf_ptr = create_number(3.14159)

print(mpf_ptr)

This just prints:

<__main__.LP_c_void_p object at 0x00000119FA0C7ED0>

How can I pass the mpf_t value from C++ and assign it to a gmpy2.mpfr in Python?

0

There are 0 answers