Partage
  • Partager sur Facebook
  • Partager sur Twitter

How can I call a c++ function using python

How can I call a c++ function using python

    22 octobre 2019 à 16:34:42

    want to know if there's a way to use a c++ function inside a python code

    For example, after doing my research I did find this solution using .dll file. But It can't find the function My code:

    fun.cpp:

    #include <iostream>
    __declspec( dllexport ) int add(int a, int b) {
    return a+b;
    }
    int main()
    {
        std::cout << "Hello World! from C++" << std::endl;
        return 0;
    }


    compiling it using cmd:

        g++ fun.cpp -o fun.dll



    Calling the function using Python, ctypes:

    from ctypes import *
    import os
    mydll = cdll.LoadLibrary("C:/Users/User/Desktop/ctypes/fun.dll")
    
    result= mydll.add(10,1)
    print("Addition value:-"+result)



    But I had this error:

    Traceback (most recent call last): File "c:\Users\User.vscode\extensions\ms-python.python-2019.10.41019\pythonFiles\ptvsd_launcher.py", line 43, in main(ptvsdArgs) File "c:\Users\User.vscode\extensions\ms-python.python-2019.10.41019\pythonFiles\lib\python\old_ptvsd\ptvsd__main__.py", line 432, in main run() File "c:\Users\User.vscode\extensions\ms-python.python-2019.10.41019\pythonFiles\lib\python\old_ptvsd\ptvsd__main__.py", line 316, in run_file runpy.run_path(target, run_name='main') File "C:\Python36\lib\runpy.py", line 263, in run_path pkg_name=pkg_name, script_name=fname) File "C:\Python36\lib\runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "C:\Python36\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "c:\Users\User\Desktop\ctypes\test.py", line 5, in result= mydll.add(10,1) File "C:\Python36\lib\ctypes__init__.py", line 361, in getattr func = self.getitem(name) File "C:\Python36\lib\ctypes__init__.py", line 366, in getitem func = self._FuncPtr((name_or_ordinal, self)) AttributeError: function 'add' not found

    -
    Edité par ouafaekandoussi2 22 octobre 2019 à 16:37:56

    • Partager sur Facebook
    • Partager sur Twitter
      22 octobre 2019 à 16:38:50

      Bonjour,

      Mauvais forum

      Le sujet est déplacé de la section Langage Python vers la section Let's talk!

      • Partager sur Facebook
      • Partager sur Twitter

      How can I call a c++ function using python

      × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
      × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
      • Editeur
      • Markdown