JNI to call .NET dll

时光毁灭记忆、已成空白 提交于 2020-01-24 17:45:07

问题


I am trying to create a Java Application that will call C# dll through an intermediate Visula C++ dll, its all well and good when I try to run the .class file from cmd prompt or Eclipse IDE but the problem is in order to do it I need to place the C# dll in the same directory as the Java.exe or else there occurs an exception the the native call, thus making to impossible to build the Java Project, any idea as to how this can be done


回答1:


You can enable and register your managed (.NET) dll with COM Interop. See this link: http://support.microsoft.com/kb/828736




回答2:


There are other ways, without COM. You might find one preferable or need one if you can't change the .NET component to support COM clients.

When a process that loads the CLR, the assembly search paths are determined by the location of the process's main Win32 module. Assembly search paths are different than Win32 DLL search paths. In this case, it starts with the location of java.exe. As a result, the search paths include the Global Assembly Cache (GAC), the folder of java.exe, and subfolders listed as assembly probing paths in java.exe.config (if it exists).

See How the Runtime Locates Assemblies.

This leads to a few options:

  1. Install the assembly in the GAC. (On an end-user machines an installer should be used but on a developer machine, you can use gacutil.)
  2. Put the assembly in the java.exe folder. Or, conversely, put a copy of Java in your application folder.
  3. Create a subfolder with write permissions for the assembly. Create or update a java.exe.config and list the subfolder as a probing path.
  4. Create your own java.exe in C or C++ using the Java Invocation API. It's documented alongside JNI. You can name it whatever you wish since, after all, it is your application. (This what many Java-based applications do, even if they don't use .NET. For example, eclipse and LibreOffice.) The documentation gives a complete example in C. For a typical MSVC build, jni.h needs to on the project's include path, jvm.lib needs to be on the project's library path, and jvm.dll needs to be in the Win32 DLL search path.

Other alternatives:

  1. The VC DLL can load the assembly explicitly from a path before the assembly is needed. See Assembly::LoadFile.
  2. Load the assembly on demand after it's not found by the standard search. See AppDomain::AssemblyResolve Event (but note it's description is wrong: failure has not occurred until and if your custom resolver(s) fails).


来源:https://stackoverflow.com/questions/24344034/jni-to-call-net-dll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!