C # Calls Java Method Instance detailed _c# tutorial

Source: Internet
Author: User

C # can directly refer to C + + DLLs and convert Java-written programs. Recently, because of the work reason contact this aspect to be more, according to the actual demand, we through a concrete example transforms a Java method to the DLL which can be called directly by C #

C # calls C + +

C # calls The example of C + + online A lot, take a C + + specific method for example.

C + + code

Gets a frame of image data Mvsmartcamctrl_api int __stdcall mv_sc_getoneframe (in void* handle, in out unsigned char *pdata, in Unsign
Ed int ndatasize, in out mv_sc_image_out_info* pstimageinfo); Result data cache upper bound #define MV_SC_MAX_RESULT_SIZE (1024*16)//output frame information typedef struct _MV_SC_IMAGE_OUT_INFO_ {unsigned short nwid Th Image width unsigned short nheight; Image high unsigned int nframenum; Frame number unsigned int nframelen; Current frame data size unsigned int ntimestamphigh; Timestamp high 32-bit unsigned int ntimestamplow; Time stamp low 32 bit unsigned int nresulttype;
The message type of the output//According to the message type corresponds to the different structure unsigned char chresult[mv_sc_max_result_size]; unsigned int nreserved[8]; Keep}mv_sc_image_out_info C # code///<summary>///Get photos taken by camera///</summary>///<param name= "Handle" >&lt ;/param>///<returns></returns> [DllImport ("MvSmartCamCtrl.dll")] public static extern int MV_SC_
Getoneframe (IntPtr handle, byte[] pData, int ndatasize, out mv_sc_image_out_info pstdevinfo); Output frame information [StructLayout (layoutkind.sequential)] Public struct Mv_sc_image_out_info {public short nwidth;//Image width public short nheight;//image high public int nframenum;//Frame number P ublic int Nframelen; Current frame data size public int ntimestamphigh; Timestamp high 32-bit public int ntimestamplow; Timestamp low 32-bit public int nresulttype; 
The message type of output//corresponds to a different structure according to the message type [MarshalAs (unmanagedtype.byvaltstr, SizeConst = 1024 *)] public mv_sc_result_bcr chresult;
[MarshalAs (UnmanagedType.ByValArray, SizeConst = 8)] public int[] nreserved; }

So we put this DLL in the program root directory, we can implement the DLL method call.

C # calls Java methods

IKVM. NET is a Java implementation of the mono and Microsoft. NET Framework designed to run Java programs on the. NET platform. It contains the following components:

Java virtual machines that are implemented with. NET, Java class libraries. NET implementation.

Committed in Java and. NET is a tool for interacting between.

Program Requirements

We have a Java-written demo, the parameters are transmitted using GZIP compression to the server, the code is as follows:

Package Demo;
Import Java.io.BufferedReader;
Import Java.io.ByteArrayInputStream;
Import Java.io.ByteArrayOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.ObjectInputStream;
Import Java.io.ObjectOutputStream;
Import Java.util.zip.GZIPInputStream;
Import Java.util.zip.GZIPOutputStream;
Import org.apache.commons.httpclient.HttpClient;
Import Org.apache.commons.httpclient.methods.PostMethod;
Import Org.apache.commons.httpclient.params.HttpClientParams;
Import Com.google.gson.Gson; 
public class Demo {public static string Dopostclient (string json, string url) {httpclient httpclient = new HttpClient ();
String rval = "";
Postmethod Postmethod = new Postmethod (URL);
try {Gson Gson = new Gson ();
InputStream in = new Bytearrayinputstream (Objecttobyte (JSON));
Postmethod.setrequestbody (in);
Httpclientparams params = new Httpclientparams ();
Httpclient.setparams (params);
Httpclient.executemethod (Postmethod); Byte[] B = PostmetHod.getresponsebody ();
String rtndata = (string) bytetoobject (b);
Rval = Gson.tojson (Rtndata); catch (Exception e) {rval= "Erro:" +e.getmessage ();}
finally {postmethod.releaseconnection ();} return rval;
public static byte[] Objecttobyte (Java.lang.Object obj) {byte[] bytes = NULL;
ObjectOutputStream oo = null;
try {bytearrayoutputstream out = new Bytearrayoutputstream ();
Gzipoutputstream gzip = new Gzipoutputstream (out);
Gzip.write (Obj.tostring (). GetBytes ("Utf-8"));
Gzip.close ();
bytes = Out.tobytearray (); catch (Exception e) {e.printstacktrace ();} finally {if (oo!= null) {try {oo.close ();} catch (IOException e) {E.P
Rintstacktrace ();
}} return bytes;
private static Java.lang.Object bytetoobject (byte[] bytes) {String obj = "";
ObjectInputStream oi = null;
try {bytearrayinputstream bi = new Bytearrayinputstream (bytes);
Gzipinputstream Gzipi = new Gzipinputstream (BI);
BufferedReader BufferedReader = new BufferedReader (new InputStreamReader (Gzipi, "UTF-8")); StringLine 
while (line = Bufferedreader.readline ())!= null) {obj+=line; } catch (Exception e) {e.printstacktrace ();} finally {if (Oi!= null) {try {oi.close ();} catch (IOException e) {E
. Printstacktrace ();
}} return obj; }
}

This code I rewritten in C #, with HttpWebRequest way to the server, the server side gzip uncompressed, check the reason is because Java and C # byte type value range, we have two solutions, One is to hang this Java made webservice on the server, C # to call again, the second is to compile this method into C # directly call the DLL, because this method is relatively single, we chose the latter.

Environment configuration

Ikvm.net downloads to extract data from the Bin folder for Jar package conversions and base DLLs.

IKVM. OpenJDK.ClassLibrary.dll is used for C # program Access.

Download Address: https://yunpan.cn/cBHTS5fXsIe9v access password 0847.

Add the address of the Ikvm.net Bin folder to the environment variable.

Right-key properties of the computer-advanced system settings-advanced-environment variables--found in system variables path--add the address of the Bin folder to the
Enter IKVMC in CMD to help document the success of the environment configuration.

The Ikvm.openjdk.core.dll,ikvm.runtime.dll,ikvm.runtime.jni.dll and IKVM.OpenJDK.ClassLibrary.dll under the Bin folder are public DLLs, and all converters need to refer to

Conversion steps

1. Determine the reference relationship:

The demo is structured as follows:

Demo.jar relies on Commons-httpclient-3.1.jar and Gson-2.4.jar.

Commons-httpclient-3.1.jar relies on Commons-logging-1.1.3.jar and Commons-codec-1.6.jar.

We will first build the Gson-2.4.jar,commons-logging-1.1.3.jar,commons-codec-1.6.jar DLL, the syntax is as follows:

IKVMC jar Package Physical path.

Win7 system default generation in C:\Users\Administrator this folder

The Commons-httpclient-3.1.dll build syntax is as follows:

Ikvmc Commons-httpclient-3.1.jar-r:commons-logging-1.1.3.dll-r:commons-codec-1.6.dll

We packaged the Demo with the name Javaapi.demo so the generated JavaApi.dll syntax is as follows:

Ikvmc Javaapi.demo.jar-r:commons-httpclient-3.1.dll-r:gson-2.4.dll

The above files are the corresponding physical paths, and then add all the generated DLLs to the C # project reference, including the previous public DLL, referenced to all referenced DLLs in the project as shown:


This way you can use this Java method directly in your program.

Demo.Demo.doPostClient (JS, url);

Package name in the first demo Java program.

The class name in the second demo Java program.

The above is a small set for you to introduce the C # call Java method Examples of all the narrative, I hope to help you, if you want to learn more content please pay attention to cloud Habitat community website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.