Search code examples
c++python-3.xctypesstdvector

How to use std::vector in extern "C" function?


I have a .dll that was written in c++ with extern "C", this function is called add and returns a double. I want transfer python's list to c++'s array, and then transfer the array to c++'s vector, so that, I can indirectly use the vector data type.

In the add.h:

#pragma once
#include <iostream>
#include <vector>

extern "C" double add(double *arr, int n);
extern "C" double add_raw(std::vector<double> vec);

In the add.cpp:

#include "add.h"

double add(double *arr, int n)
{
    std::vector<double> vec(arr, arr + n);
    return add_raw(vec);
}

double add_raw(std::vector<double> vec)
{
    double sum{};
    //here some algrothm developed by vector<double>!!!
    return sum;
}

In add.cpp's code, I referred to the link https://stackoverflow.com/a/49747364/14641812;

In the test.py:

import ctypes

my_dll = ctypes.cdll.LoadLibrary("libAddDll.dll")
my_dll.add.argtypes = [ctypes.POINTER(ctypes.c_double), ctypes.c_int]
my_dll.add.restype = ctypes.c_double
mylist = [1, 2, 3, 4, 5]
myvec = (ctypes.c_double * len(mylist))(*mylist)
result = my_dll.add(myvec, len(mylist))
print(result)

But I get the following error:

Traceback (most recent call last):
  File "f:\test\03cpp\c++\TestExternalCpp\Test\test1.py", line 11, in <module>
    my_dll = ctypes.cdll.LoadLibrary("./dlls/libAddDll.dll")
  File "D:\Python310\lib\ctypes\__init__.py", line 452, in LoadLibrary
    return self._dlltype(name)
  File "D:\Python310\lib\ctypes\__init__.py", line 374, in __init__
    self._handle = _dlopen(self._name, mode)
FileNotFoundError: Could not find module 'F:\test\03cpp\c++20\TestExternalCpp\Test\dlls\libAddDll.dll' (or one of its dependencies). Try using the full path with constructor syntax.

Python Version:Python 3.10.10 GCC Version: gcc version 13.1.0 (MinGW-W64) How to fix it? Thanks.


Solution

  • After several days of searching, the problem was solved by copying the three files libgcc_s_seh-1.dll, libstdc++-6.dll, and libwinpthread-1.dll from the GCC compiler to the directory where the libAddDll.dll file is located.