我在Xamarin中有一个Mac的控制台项目,并且想使用外部库中的c ++函数。但是不幸的是,当我尝试像这样使用DLLIMPORT(c#)时:

[DllImport('path to the library')]
static extern double sum(double x, double y);

public static void Main(string[] args)
{
   Console.WriteLine(sum(2,2));
}


我得到System.DLLNotFoundException。但是,它适用于系统库:

[DllImport("/usr/lib/libSystem.dylib")]
static extern IntPtr dlopen(string path, int mode);


这是我所有的代码:

1)main.cpp(来自lib.dylib库):

extern "C" double sum(double x, double y) {
   return x + y;
}


2)Program.cs(来自Xamarin C#Project):

using System;
using System.Runtime.InteropServices;

namespace Project {
   class MainClass {
      [DLLImport("/full/path/to/lib.dylib")]
      static extern double sum(double x, double y);

      public static void Main(string[] args) {
         Console.WriteLine(sum(2,2));
         Console.ReadKey();
      }
   }
}


我使用XCode创建库(.dylib),但不确定我是否做对了所有事情。

最佳答案

我想我知道错在哪里。
我在c#中引用库的方式是可以的。问题是我错误地构建了库。让我解释。

要创建该库,我使用Mac OS XCode库项目(框架:无(纯C / C ++库)):

press here to view image

这意味着默认情况下,“构建设置”选项卡中的“建筑”面板如下所示:

press here to view image

注意突出显示的属性。它们很重要。
因此,如果我按原样放置它,然后按cmd + B(构建),我将获得一个库(.dylib文件)。但是,如果我去终端并用lipo检查这个库,我会得到:

lipo -info path/to/the/library.dylib
Non-fat file: path/to/the/library.dylib is architecture: x86_64


但是,如果我对/usr/lib/libSystem.B.dylib库(或任何其他系统.dylib库)执行相同的操作,则输出将不同:

lipo -info /usr/lib/libSystem.B.dylib
Architectures in the fat file: /usr/lib/libSystem.B.dylib are: x86_64 i386


很容易猜到我在检查自己的库时希望看到相同的内容。要修复此问题,请返回“架构”面板,然后执行以下操作:

1)检查“有效架构”属性。它的值必须是“ i386 x86_64”(不带引号)。

2)对于“仅构建活动体系结构”属性,选择“否”。到目前为止,“架构”面板必须如下所示:

press here to view image

3)按下“建筑”属性。选择“其他...”作为值,然后在打开的窗口中键入:

${ARCHS_STANDARD}
x86_64
i386


press here to view image

因此,“架构”面板必须如下所示:

press here to view image

就这样!现在您可以构建您的库了!如果您现在用lipo检查,您将获得:

lipo -info /path/to/your/library.dylib
Architectures in the fat file: /path/to/your/library.dylib are: x86_64 i386


我不确定有什么区别,但是奇怪的是它可以解决问题。现在我可以从c#调用我的c ++函数。

有人知道会发生什么吗?

09-10 03:07
查看更多