example - python3 ctypes install



Python ctypes cdll.LoadLibrary,實例化一個對象,執行其方法,私有變量地址被截斷 (1)

我在c中編寫了一個dll庫,使用vs2017 64位編譯,並嘗試使用64位python3.6加載它。 但是,對象的成員變量的地址被截斷為32位。

這是我的sim.c文件,它被編譯為sim.dll:

class Detector {
public:
    Detector();
    void process(int* pin, int* pout, int n);

private:
    int member_var;
};

Detector::Detector()
{
    memset(&member_var, 0, sizeof(member_var));
    myfile.open("addr_debug.txt");
    myfile << "member_var init address: " << &member_var << endl;
}
void Detector::process(int* pin, int* pout, int n);
{
    myfile << "member_var process address: " << &member_var << endl;
    myfile.close();
}

#define DllExport   __declspec( dllexport )  

extern "C" {
    DllExport Detector* Detector_new() { return new Detector(); }
    DllExport void Detector_process(Detector* det, int* pin, int* pout, int n)
    {
        det->process(pin, pout, n);
    }
}

這是我的python腳本:

from ctypes import cdll
lib = cdll.LoadLibrary(r'sim.dll')

class Detector(object):
    def __init__(self):
        self.obj = lib.Detector_new()

    def process(self,pin, pout, n):
        lib.Detector_process(self.obj,pin, pout, n)

detector = Detector()

n = 1024
a = np.arange(n, dtype=np.uint32)
b = np.zeros(n, dtype=np.int32)

aptr = a.ctypes.data_as(ctypes.POINTER(ctypes.c_int))
bptr = b.ctypes.data_as(ctypes.POINTER(ctypes.c_int))

detector.process(aptr, bptr, n)

這是addr_debug.txt中member_var的地址:

member_var init address:    0000025259E123C4
member_var process address: 0000000059E123C4

因此訪問它會觸發內存訪問錯誤:

OSError: exception: access violation reading 0000000059E123C4

我試圖了解這個問題的一些嘗試:

  • 將member_var定義為public而不是private,而不是幫助,地址仍然被截斷。
  • 將member_var定義為全局變量,然後地址就可以了。 所以我猜想在將對象返回到python或將對像傳遞回dll時會發生member_var地址截斷。

Always(CORRECTLY)為 C中 定義的函數指定 argtypes restype ,否則( C89 樣式)它們將 默認為 int 32bit ),生成 !!! 未定義的行為! 。 在 64位 ,它可能會導致截斷(這正是您正在經歷的)。

此外,遇到問題時,不要忘記 [Python 3.Docs]:ctypes - Python的外部函數庫

下面是您的代碼的改編版本。

detector.cpp

#include <stdio.h>
#include <memory.h>
#include <fstream>

#define C_TAG "From C"
#define PRINT_MSG_2SP(ARG0, ARG1) printf("%s - [%s] (%d) - [%s]:  %s: 0x%0p\n", C_TAG, __FILE__, __LINE__, __FUNCTION__, ARG0, ARG1)


using std::endl;

std::ofstream outFile;


class Detector {
    public:
        Detector();
        void process(int *pIn, int *pOut, int n);

    private:
        int m_var;
};


Detector::Detector() 
: m_var(0) {
    outFile.open("addr_debug.txt");
    outFile << "m_var init address: " << &m_var << endl;
    PRINT_MSG_2SP("&m_var", &m_var);
}

void Detector::process(int *pIn, int *pOut, int n) {
    outFile << "m_var process address: " << &m_var << endl;
    outFile.close();
    PRINT_MSG_2SP("&m_var", &m_var);
}


#define SIM_EXPORT __declspec(dllexport)

#if defined(__cplusplus)
extern "C" {
#endif

    SIM_EXPORT Detector *DetectorNew() { return new Detector(); }
    SIM_EXPORT void DetectorProcess(Detector *pDet, int *pIn, int *pOut, int n) {
        pDet->process(pIn, pOut, n);
    }
    SIM_EXPORT void DetectorDelete(Detector *pDet) { delete pDet; }

#if defined(__cplusplus)
}
#endif

code.py

import sys
from ctypes import CDLL, POINTER, \
    c_int, c_void_p
import numpy as np


sim_dll = CDLL("./sim.dll")

detector_new_func = sim_dll.DetectorNew
detector_new_func.restype = c_void_p

detector_process_func = sim_dll.DetectorProcess
detector_process_func.argtypes = [c_void_p, POINTER(c_int), POINTER(c_int), c_int]

detector_delete_func = sim_dll.DetectorDelete
detector_delete_func.argtypes = [c_void_p]


class Detector():
    def __init__(self):
        self.obj = detector_new_func()

    def process(self, pin, pout, n):
        detector_process_func(self.obj, pin, pout, n)

    def __del__(self):
        detector_delete_func(self.obj)


def main():
    detector = Detector()

    n = 1024
    a = np.arange(n, dtype=np.uint32)
    b = np.zeros(n, dtype=np.int32)

    aptr = a.ctypes.data_as(POINTER(c_int))
    bptr = b.ctypes.data_as(POINTER(c_int))

    detector.process(aptr, bptr, n)


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

備註

  • 正如我在開頭所說,問題是 argtypes restype 沒有被指定(例如對於 DetectorNew :註釋 detector_new_func.restype = c_void_p ,你會再次遇到問題)
  • 問題中的代碼是缺少部分( #include s, import s,...),也有一些語法錯誤,因此它不編譯,因此不遵循 [SO]:如何創建Minimal,完整且可驗證的示例(mcve) 指南。 請問 時確保有 mcve
  • 您分配的對象( new Detector() )也必須被釋放(否則,它將產生 內存洩漏 ),所以我添加了一個函數( DetectorDelete - 要做到這一點),這是從( Python Detector 的調用析構函數
  • 其他(非關鍵)更改(標識符重命名,一點重構,打印到 stdout ,......)

輸出

(py35x64_tes1) e:\Work\Dev\\q052268294>"c:\Install\x86\Microsoft\Visual Studio Community\2015\vc\vcvarsall.bat" x64

(py35x64_test) e:\Work\Dev\\q052268294>dir /b
code.py
detector.cpp

(py35x64_test) e:\Work\Dev\\q052268294>cl /nologo /DDLL /EHsc detector.cpp  /link /DLL /OUT:sim.dll
detector.cpp
   Creating library sim.lib and object sim.exp

(py35x64_test) e:\Work\Dev\\q052268294>dir /b
code.py
detector.cpp
detector.obj
sim.dll
sim.exp
sim.lib

(py35x64_test) e:\Work\Dev\\q052268294>"e:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" ./code.py
Python 3.5.4 (v3.5.4:3f56838, Aug  8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32

From C - [detector.cpp] (28) - [Detector::Detector]:  &m_var: 0x0000020CE366E270
From C - [detector.cpp] (34) - [Detector::process]:  &m_var: 0x0000020CE366E270




ctypes