Skip to Main Content

Java HotSpot Virtual Machine

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to use a C# dll with JNI

843829Jul 29 2009 — edited Sep 11 2009
After a ton of issues, I finally got this working properly. I've come across a lot of forum posts about the various problems and VERY few answers so I thought I would post my solution here.

To do this, you need to create a managed C++ layer in between C# and java. The JNI functions in C++ dll can make calls to the C# dll directly, and your java program can make calls directly to the native JNI functions. Some important notes on using C# classes in C++ are:

-gcroot<CSClass ^> should be used on any objects that are instances of some C# class.
-the symbol ^ should be used with all C# references (its the symbol for references)
-gcnew should be used to allocate C# objects
-in visual studio, add the C# dll as a reference rather than using #using <CsDLL.dll>
-do not use #using <CsDLL.dll>

The next issue is loading the libraries. By adding the folder your C++ dll is located in to the Djava.library.path VM argument, you can load your C++ library with System.LoadLibrary("Cppdll.dll"). You DO NOT need to load the C# dll in your java program. In fact, it will ignore you if you try. The problem with loading this dll is with how the CLR searches for referenced assemblies. The CLR First searches the DEVPATH environment variable (if the machine.config file has developer mode set to on), then it searches the GAC, then it searches the codebases, then it searchs the current executable's directory along with a list of definable subdirectories (probes).

DEVPATH is a decent option, but it requires modifying the machine.config file to be in developer mode. Once that is done, it acts just like the PATH environment variable.

If your C# dlls are strongly named, I would recommend adding them to the GAC or using codebases. However I have not done this and am not sure how.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 9 2009
Added on Jul 29 2009
3 comments
777 views