有没有一种方法可以实时更新动态库中的变量值?

时间:2020-02-22 22:42:09

标签: c++ linux shared-libraries ctypes

我建立了一个动态共享库,其中包含一个内部包含变量的简单结构。我的主程序是C ++,该程序实时更改struct的值。

我希望python脚本能够实时使用更新后的值。

但是,当前的python脚本(使用ctypes)无法获取更新后的值。

有没有办法做到这一点?有可能这样做吗?

当前的python看起来像这样( script.py ):

#!/usr/bin/env python3
import sys
import ctypes

# pulls library made from c++
lib = ctypes.cdll.LoadLibrary('./libsharedObject.so')

# init constructor
lib.object_new.argtypes = []
lib.object_new.restype = ctypes.c_void_p


# init do_something function
lib.object_do_something.argtypes = [ctypes.c_void_p]
lib.object_do_something.restype = ctypes.c_float

class Object:
    def __init__(self):
        self.obj = lib.object_new()
        print("`Object` instance (as a `void *`): 0x{:016X}".format(self.obj))

    def do_something(self):
        return lib.object_do_something(self.obj)


def main():
    print("Testing Library...")
    obj = Object()
    ret = obj.do_something()
    print(ret)

if __name__ == "__main__":
    print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
    main()

共享库文件( sharedObject.h ):

// Data Structure for Raspberry Pi 
struct UAVTlm_t { 
    float       distance;      // distance
    UAVTlm_t(){
        distance = 7.12;
    }

    float do_something();

};

sharedObject.cpp

#include "sharedObject.h"    
struct UAVTlm_t;

float UAVTlm_t::do_something() {
    return distance;
}

extern "C" {
    UAVTlm_t *object_new(){
        return new UAVTlm_t;
    }

    float object_do_something(UAVTlm_t *pObj) { 
        return pObj->do_something(); 
    }
}

该库使用以下行构建:

$ g++ -shared -fPIC -o libsharedObject.so sharedObject.cpp -lstdc++

0 个答案:

没有答案