Lazarus 库在 Python 中使用 ctypes for OSX

Lazarus library using ctypes in Python for OSX

我在 Lazarus 中有一个非常小的库,我无法在我的 Mac 上将它与 ctypes 一起使用。我真的不明白我做错了什么,我希望有人能指出我正确的方向。

这是我在 Lazarus 中的代码。在 Linux machine (Ubuntu VM) 上编译时,一切正常。我可以创建一个 Linux .so 文件,并使用 ctypes,我可以调用共享库。

library project1;

{$mode delphi}{$H+}

{$IFDEF Darwin}
{$linkframework CoreFoundation}
{$linkframework Carbon}
{$ENDIF}

function SubStr(CString: PChar;FromPos,ToPos: Longint): PChar; cdecl;

var
  Length: Integer;

begin
  Length := StrLen(CString);
  SubStr := CString + Length;
  if (FromPos > 0) and (ToPos >= FromPos) then
  begin
    if Length >= FromPos then
      SubStr := CString + FromPos - 1;
    if Length > ToPos then
    CString[ToPos] := #0;
  end;
end;

exports
  SubStr;

end.

Python 代码如下。

import ctypes

lib = ctypes.CDLL('./libproject1.so')


lib.SubStr.argtypes = (ctypes.c_char_p, ctypes.c_int64, ctypes.c_int64)
lib.SubStr.restype = ctypes.c_char_p

lib.SubStr('HelloWorld', 1, 5)
# The output is 'Hello' as expected

然而,当我在 Mac 上测试同样的东西时,我得到以下错误。

---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-44-37971b70da86> in <module>()
      1 import ctypes
      2 
----> 3 ctypes.CDLL('./libproject1.dylib')

/Users/$USER/miniconda2/lib/python2.7/ctypes/__init__.pyc in __init__(self, name, mode, handle, use_errno, use_last_error)
    360 
    361         if handle is None:
--> 362             self._handle = _dlopen(self._name, mode)
    363         else:
    364             self._handle = handle

OSError: dlopen(./libproject1.dylib, 6): no suitable image found.  Did find:
    ./libproject1.dylib: mach-o, but wrong architecture

我在 mac 上创建了一个新项目并尝试了同样的事情但无济于事。

在此 dylib 上使用 lipo 时,我得到以下输出。

$ lipo -info libproject1.dylib
Non-fat file: libproject1.dylib is architecture: i386

我相信这是我应该得到的。有人对如何解决这个问题有任何建议吗?

Miniconda 显然是 Python 的 64 位版本。您的库是 32 位的。 (i386 的体系结构是 32 位;对于 64 位库,您应该看到 x86_64。)因此,Python 正确报告 "wrong architecture."

Recompile your library as a 64-bit binary 然后重试。