简体   繁体   English

从C ++ DLL访问C#静态类

[英]Access C# static class from a C++ DLL

I've been tasked with writing a new interface to a legacy C++ DLL I don't have the source code for, which - for reasons beyond me - accesses a global class in the legacy application directly. 我的任务是编写一个我没有源代码的旧C ++ DLL的新接口,出于我自己的原因,它直接在旧应用程序中访问全局类。

From the application, it's something like: 在应用程序中,它类似于:

extern Interface *App;

...

Interface App*;   //  A pointer to our interface class.

Then, from the legacy DLL: 然后,从旧版DLL中:

if( App->GetStatus() ) return false;

The Interface class that App refers to is quite trivial to rewrite in C#, but how can I make it the equivalent of extern so that the legacy C++ DLL can access it? App引用的Interface类非常容易用C#重写,但是如何使它等效于extern以便旧的C ++ DLL可以访问它?

Thanks! 谢谢!

You could try using Robert Giesecke's " UnmanagedExports " nuget package to achieve this functionality like so: 您可以尝试使用Robert Giesecke的“ UnmanagedExports ” nuget软件包来实现此功能,如下所示:

class Test
{
    [DllExport("add", CallingConvention = CallingConvention.Cdecl)]
    public static int TestExport(int left, int right)
    {
       return left + right;
    } 
}

However : 但是

a) I believe this only works for methods, not classes and a)我相信这仅适用于方法,不适用于类和

b) the reason there isn't a native way to export a DLL in C# is because that the calling application must have the .NET framework loaded in order to access that entry point. b)之所以没有用C#导出DLL的本机方法,是因为调用应用程序必须加载.NET框架才能访问该入口点。 This also applies to the UnmanagedExports nuget package that I linked to above. 这也适用于我上面链接到的UnmanagedExports nuget包。

You can hack your way around this by getting your C++ app to load mono before calling the C# app, but it doesn't sound like this is possible in your case. 您可以通过在调用C#应用程序之前让C ++应用程序加载mono来解决此问题,但这听起来并不可行。

(Also, UnmanagedExports will only work if you explicitly set a build target in your project's properties - eg. x86) (此外,仅当您在项目属性中明确设置了构建目标时,UnmanagedExports才起作用-例如,x86)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM