在Python中打开共享对象文件时出错(OSError: 无法打开共享对象文件:没有这样的文件或目录)

2 投票
1 回答
3608 浏览
提问于 2025-04-18 07:23

我正在做一个简单的程序,目的是从Python中调用C++的函数。我在运行这个代码的设备是树莓派,操作系统是Raspbian。在这里,我使用ctypes来从Python调用C++。以下是我的C++代码test.cpp:

#ifdef __cplusplus
extern "C"
#endif
class cppmax
{
int num1;
int num2;
int max(num1,num2) 
{
  // local variable declaration
  int result;

  if (num1 > num2)
    result = num1;
  else
    result = num2;

  return result; 
}
};

还有我的另一个Python代码是test.py:

from ctypes import *

cmax = cdll.LoadLibrary('./test.dll').max
cmax.argtypes = [c_int, c_int] # arguments types
cmax.restype = c_int           # return type, or None if void
a = int(raw_input("Enter 1st no"))
b = int(raw_input("Enter 2nd no"))
print "Your answer is :", cmax(a,b)

这些代码在Ubuntu上运行得很好,但在树莓派上却出现了错误,错误信息是:

Traceback (most recent call last)
  File "test.py", line 3, in <module>
    cmax=cdll.LoadLibrary('/home/pi/calling+cpp/test.dll').max
  File "/usr/lib/python2.7/ctypes/_init_.py", line 365, in _init_
    self._handle = _dlopen(self._name, mode)
OSError: /home/pi/calling_cpp/test.dll: cannot open shared object file: No such file or directory

在编译C++代码时,我使用的命令是:

g++ -Wall test.cpp -shared -o test.dll

我尝试过在问题中提到的方法:无法打开共享对象文件:没有这样的文件或目录,但是没有成功。

1 个回答

0

在Linux系统中,find_library()这个函数会尝试运行一些外部程序(比如/sbin/ldconfig、gcc和objdump)来找到库文件。它会返回库文件的文件名。

你可以尝试在/etc/ld.so.conf文件中添加一行/usr/local/lib,然后运行sudo ldconfig命令。

链接:http://blog.csdn.net/wolfzhaoshuai/article/details/46520371(中文)

按照这个方法,我解决了类似的问题。

撰写回答