首页 > 解决方案 > 在 python 中使用 c++ 函数时出错:OSError: [WinError 193] %1 is not an valid Win32 application

问题描述

我正在尝试用 c++ 为我用 python 制作的游戏编写一个数学库。我尝试按照 Florian Bosch 在这个问题中回答的步骤进行操作。

这是c ++中的代码

#include <iostream>
class math
{
public:
    void print()
    {
        std::cout << "hello" << std::endl;
    }
};

extern "C"
{
    __declspec(dllexport) math* mathNew()
    {
        return new math();
    }

    __declspec(dllexport) void assignMath(math* mathObject)
    {
        mathObject->print();
    }
}

这是python中的代码。

from ctypes import cdll
lib = cdll.LoadLibrary('./math.so')

class Math:
    def __init__(self):
        self.object = lib.mathNew()

    def print(self):
        lib.print = (self.object)

math = Math()
math.print()

这是我制作 .o 和 .so 文件的方法。

 g++ -c -fPIC math.cpp -o math.o 
 g++ -shared -Wl,-soname,math.so -o math.so  math.o

这是我收到的完整错误消息。

Traceback (most recent call last):
  File "C:\Users\me\OneDrive\Documents\A level python codes\project-actual proper final\main.py", line 2, in <module>
    lib = cdll.LoadLibrary('./math.so')
  File "C:\Users\me\AppData\Local\Programs\Python\Python38\lib\ctypes\__init__.py", line 447, in LoadLibrary
    return self._dlltype(name)
  File "C:\Users\me\AppData\Local\Programs\Python\Python38\lib\ctypes\__init__.py", line 369, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: [WinError 193] %1 is not a valid Win32 application

 File "C:\Users\me\AppData\Local\Programs\Python\Python38\lib\ctypes\__init__.py", line 369, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: [WinError 193] %1 is not a valid Win32 application

标签: pythonc++cpython-3.x

解决方案


推荐阅读