0

I call C function in python using ctypes,but Python can't get correct address passed by C function.

import ctypes

if __name__ == '__main__':
    api = ctypes.CDLL('path_to_my_so')
    api.CreateSDK.restype = ctypes.c_void_p
    context = api.CreateSDK()

    print (context)
    print (ctypes.c_void_p(context).value)
    api.Detect(context)
#include "sdk.h"
#include <iostream>

using namespace std;

class SDK{
public:
    SDK():data(100){};
    int data;
};

ModelHandle CreateSDK(){
    ModelHandle sdk = new SDK();
    cerr << "address of sdk to give:" << sdk << endl;
    return sdk;
}

void Detect(ModelHandle sdk){
    cerr << "address of given sdk:" << sdk << endl;
    cerr << static_cast<SDK*>(sdk)->data << endl;
}
#pragma once

extern "C"{
    typedef void* ModelHandle;

    ModelHandle CreateSDK();

    void Detect(ModelHandle sdk);
}

I excpet address output by C are the same,but here is the thing I got:

94731076196768

94731076196768

address of sdk to give:0x56284c2559a0

address of given sdk:0x4c2559a0

  • Memory address formatting in Python is different than that of C. Try reformatting the memory address that you get form SDK – Akhilesh Sharma Aug 28 '19 at 10:09
  • 1
    Possible duplicate of [Python ctypes cdll.LoadLibrary, instantiate an object, execute its method, private variable address truncated](https://stackoverflow.com/questions/52268294/python-ctypes-cdll-loadlibrary-instantiate-an-object-execute-its-method-priva). Add `api.Detect.argtypes = [ctypes.c_void_p]`. Also, *Detect* prototype in *C* is incorrect. It should be: `void Detect(ModelHandle *sdk);` – CristiFati Aug 28 '19 at 10:11

0 Answers0