从C调用C#DLL;链接问题

从C调用C#DLL;链接问题,c#,c,visual-studio-2012,dll,C#,C,Visual Studio 2012,Dll,我正在使用VS2012,并试图从我编写的C DLL中调用C#项目中的函数。外部应用程序(Thunderbird)调用C DLL 我已经找到了这一页,并按照说明进行了操作。在这个过程中,我的C#项目必须设置为.net4和x86,以便尽可能地编译和链接所有内容。但我有一个链接器错误,我无法解决,因为这是我未知的领域,可能我只是在做一些愚蠢的事情 在我的C#中,我有 在我的C里我有 #include<stdio.h> int add(int left, int right); //i

我正在使用VS2012,并试图从我编写的C DLL中调用C#项目中的函数。外部应用程序(Thunderbird)调用C DLL

我已经找到了这一页,并按照说明进行了操作。在这个过程中,我的C#项目必须设置为.net4和x86,以便尽可能地编译和链接所有内容。但我有一个链接器错误,我无法解决,因为这是我未知的领域,可能我只是在做一些愚蠢的事情

在我的C#中,我有

在我的C里我有

 #include<stdio.h>

 int add(int left, int right); //in c#

 __declspec(dllexport)char* strTest2()
 {
    int i = add(2,3);
    char *p = "C:\\Work\\Mozilla\\Test dir\\testfile.zip";
    return p;
 }
#包括
整数相加(整数左,整数右)//在c中#
__declspec(dllexport)字符*strTest2()
{
int i=加(2,3);
char*p=“C:\\Work\\Mozilla\\Test dir\\testfile.zip”;
返回p;
}
C项目在其外部依赖项中引用C#项目

在构建时,我得到链接器错误“error LNK2019:unresolved external symbol\u add referenced in function\u strest2”

如果我使用DllExp查看C#DLL,那么我看不到任何导出内容。我应该吗?我本来希望看到“add”函数,但它不在那里,而且在我自己构建C#DLL时也没有生成任何错误


此外,如果事情在链条的后面运行,那么C代码中的“add”原型就是我所需要的吗?

我最近尝试出于同样的目的导出C函数(使用RGiesecke的库和其他方法),但无法让它工作,并且发现它非常复杂。如果您可以尝试其他方法,我建议您考虑编写一个C++/CLI库作为中介。对我来说,这是一个更具互操作性的解决方案


这里有一个不错的教程:

您可能需要使用字符串参数的编组属性定义c#签名

[DllImport(@"c:\GDAit.dll")]
public static extern long TransGeogPt([MarshalAs(UnmanagedType.LPStr)] string sGridFile, long lDirection, double dLat, double dLong, ref double pdLatNew, ref double pdLongNew, ref double pdLatAcc, ref double pdLongAcc);

[DllImport(@"c:\GDAit.dll")]
public static extern long TransProjPt([MarshalAs(UnmanagedType.LPStr)] string sGridFile, long lDirection, double dLat, double dLong, long lZone, ref double pdLatNew, ref double pdLongNew, ref double pdLatAcc, ref double pdLongAcc);
我还将借鉴马克·索乌尔的答案,说试试用StdCall而不是Cdecl打电话


此外,作为预防措施,我可能会再次检查以确保编译器设置为编译x86代码,以防编译64位

时,您需要为DLL提供一个导入库,以使链接器满意。你没有一个,也无法从该实用程序中获得一个。编写.def文件并将其转换为导入库在技术上是可行的,尽管很容易出错。这对于真正的应用程序来说并不实用。使用。谢谢,这和@HansPassant的评论让我又向前迈进了一步。
[DllImport(@"c:\GDAit.dll")]
public static extern long TransGeogPt([MarshalAs(UnmanagedType.LPStr)] string sGridFile, long lDirection, double dLat, double dLong, ref double pdLatNew, ref double pdLongNew, ref double pdLatAcc, ref double pdLongAcc);

[DllImport(@"c:\GDAit.dll")]
public static extern long TransProjPt([MarshalAs(UnmanagedType.LPStr)] string sGridFile, long lDirection, double dLat, double dLong, long lZone, ref double pdLatNew, ref double pdLongNew, ref double pdLatAcc, ref double pdLongAcc);