我在 Mac OS X 10.6.4 上使用 swig 2.0.1 + mono 2.6/2.8。
整体构建没问题,C# 示例的构建也没问题。问题是,当我运行示例(mono runme.exe)时,我总是收到以下错误。
Unhandled Exception: System.TypeInitializationException: An exception was thrown by the type initializer for examplePINVOKE ---> System.TypeInitializationException: An exception was thrown by the type initializer for SWIGExceptionHelper ---> System.DllNotFoundException: example
at (wrapper managed-to-native) examplePINVOKE/SWIGExceptionHelper:SWIGRegisterExceptionCallbacks_example (examplePINVOKE/SWIGExceptionHelper/ExceptionDelegate,examplePINVOKE/SWIGExceptionHelper/ExceptionDelegate,examplePINVOKE/SWIGExceptionHelper/ExceptionDelegate,examplePINVOKE/SWIGExceptionHelper/ExceptionDelegate,examplePINVOKE/SWIGExceptionHelper/ExceptionDelegate,examplePINVOKE/SWIGExceptionHelper/ExceptionDelegate,examplePINVOKE/SWIGExceptionHelper/ExceptionDelegate,examplePINVOKE/SWIGExceptionHelper/ExceptionDelegate,examplePINVOKE/SWIGExceptionHelper/ExceptionDelegate,examplePINVOKE/SWIGExceptionHelper/ExceptionDelegate,examplePINVOKE/SWIGExceptionHelper/ExceptionDelegate)
at examplePINVOKE+SWIGExceptionHelper..cctor () [0x00000] in :0
--- End of inner exception stack trace ---
at examplePINVOKE..cctor () [0x00000] in :0
--- End of inner exception stack trace ---
at example.gcd (Int32 x, Int32 y) [0x00000] in :0
at runme.Main () [0x00000] in :0
看起来好像没有找到示例库,但生成的库是libexample.so。
这是生成libexample.so的库的源码
double Foo = 3.0;
int gcd(int x, int y) {
...
}
这是使用 libexample.so 的 C# 源代码。
using System;
public class runme
{
static void Main()
{
int x = 42;
int y = 105;
int g = example.gcd(x,y);
...
}
}
这是使用 SWIG 生成的包装函数。
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.1
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
using System;
using System.Runtime.InteropServices;
public class example {
public static int gcd(int x, int y) {
int ret = examplePINVOKE.gcd(x, y);
return ret;
}
public static double Foo {
set {
examplePINVOKE.Foo_set(value);
}
get {
double ret = examplePINVOKE.Foo_get();
return ret;
}
}
}
这是获取库和执行所需运行的命令。
gcc -c example.c example_wrap.c
cc -bundle -undefined suppress -flat_namespace example.o example_wrap.o -o libexample.so
make -f ../../Makefile CSHARPSRCS='*.cs' CSHARPFLAGS='-nologo -out:runme.exe' csharp_compile
gmcs -nologo -out:runme.exe *.cs
可能出了什么问题?应该怎么做才能让 mono 了解 libexample.so?
ADDED
我可以使用“swig -csharp -dllimport“libexample.so”example.i”,但我得到了相同的结果。
我附上示例PINVOKE.cs.
正如本文中所写post,我运行了“MONO_LOG_LEVEL=debug mono runme.exe”。该消息表示即使文件存在,单声道也无法找到 ./libexample.so。
Mono: DllImport loading library: './libexample.so'.
Mono: DllImport error loading library '(null)'.
SOLUTION
我可以更改 swig/Examples 中的 Makefile 来解决这个问题。
CFLAGS = -arch i386