c++ python ctypes 依赖问题

0 投票
1 回答
41 浏览
提问于 2025-04-12 05:19

我正在尝试让我的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++代码的某些部分,看看是否只有特定部分有问题。结果发现,如果我删除优先队列的部分,只保留主函数和下界函数,其他部分就能正常工作。所以问题可能出在使用向量或优先队列上,尽管单独包含它们时并没有报错。

1 个回答

0

我通过在g++的命令中加上'-static'这个标志,解决了这个问题,这样就去掉了依赖关系。

撰写回答