问题
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:
- 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
.) - Put the assembly in the
java.exe
folder. Or, conversely, put a copy of Java in your application folder. - Create a subfolder with write permissions for the assembly. Create or update a
java.exe.config
and list the subfolder as a probing path. - 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, andjvm.dll
needs to be in the Win32 DLL search path.
Other alternatives:
- The VC DLL can load the assembly explicitly from a path before the assembly is needed. See Assembly::LoadFile.
- 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