c++ python ctypes 依赖问题

问题描述 投票:0回答:1

我试图让我的 python 程序使用 C++ 代码,但出现依赖错误。

这是我转换成dll文件的c++代码:

#include <stdio.h>
#include <algorithm>
#include <queue>
#include <vector>

using namespace std;

extern "C" {
    int b_search(int* arr, int size, int v) {
        auto it = lower_bound(arr, arr + size, v);
        int outp = distance(arr, it);
        return outp;
    }
}

vector<priority_queue<int>> Vpqs;

extern "C" {
    int p_queue(int* arr, int size) {
        priority_queue<int> outp;
        for (int i = 0; i < size; i++) {
            outp.push(arr[i]);
        }
        Vpqs.push_back(outp);
        return Vpqs.size() - 1;
    }
    int empty_p_queue() {
        priority_queue<int> outp;
        Vpqs.push_back(outp);
        return Vpqs.size() - 1;
    }
    void pq_push(int pq, int item) {
        Vpqs[pq].push(item);
    }
    int pq_pop(int pq) {
        int outp = Vpqs[pq].top();
        Vpqs[pq].pop();
        return outp;
    }
    int pq_size(int pq) {
        return Vpqs[pq].size();
    }
    int* pq_to_array(int pq) {
        priority_queue<int> pq_copy = Vpqs[pq];
        int pq_size = pq_copy.size();
        int* outp = new int[pq_size];
        for (int i = 0; i < pq_size; ++i) {
            outp[i] = pq_copy.top();
            pq_copy.pop();
        }
        return outp;
    }
}

int main() {
    return 0;
}

然后我尝试将其转换为dll文件。我在终端中使用了这个命令:

g++ -fPIC -shared -o qolc.dll clibrary.cpp -lstdc++

然后我尝试使用 python ctypes 导入它:

cppcode = ctypes.CDLL(path.dirname(path.abspath(__file__)) + '\\QoL\\clibrary\\clibrary\\qolc.dll')`

我收到此错误:

Traceback (most recent call last):
  File "D:\Python\game_engine\.venv11\Lib\site-packages\QoL.py", line 28, in <module>
    cppcode = ctypes.CDLL(path.dirname(path.abspath(__file__)) + '\\QoL\\clibrary\\clibrary\\qolc.dll')
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python311\Lib\ctypes\__init__.py", line 376, in __init__
    self._handle = _dlopen(self._name, mode)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: Could not find module 'D:\Python\game_engine\.venv11\Lib\site-packages\QoL\clibrary\clibrary\qolc.dll' (or one of its dependencies). Try using the full path with constructor syntax.

我尝试做一些研究,但没有找到解决方案。

问题不应该出在dll文件的位置上:

print(Path(path.dirname(path.abspath(__file__)) + '\\QoL\\clibrary\\clibrary\\qolc.dll').exists())
>>>True

另外,我尝试删除部分 C++ 代码,看看是否仅特定部分存在问题,似乎如果我删除代码的优先级队列部分,只保留主函数和下界函数,其余部分就可以工作,所以问题可能出在使用向量或优先级队列上,即使仅包含它们并不会引发任何错误。

python c++ terminal dependencies ctypes
1个回答
0
投票

我解决了问题,但以防万一将来有人也需要该解决方案,您需要将标志“-static”添加到 g++ 终端命令中以删除依赖项。

© www.soinside.com 2019 - 2024. All rights reserved.