Read Catalogue
- C # calls C + +
- C # calling Java methods
C # can refer directly to C + + DLLs and convert Java-written programs. Recently, due to the number of working reasons contact, according to the actual needs, we have a specific example to convert a Java method into a DLL that can be called directly by C #
Back to directory C # call C + +
C # calls C + + examples on the Web, taking a specific method of C + + as an example.
C + + code
Get a frame of image data Mvsmartcamctrl_apiint __StdCallMv_sc_getoneframe(Invoid* Handle, in-outUnsigned Char*pdata, inUnsigned IntNdatasize, in Out mv_sc_image_out_info* pstimageinfo);Upper limit of result data cache#Define Mv_sc_max_result_size (1024*16)Output frame Informationtypedefstruct _mv_sc_image_out_info_{UnsignedShort nwidth;Image widthUnsignedShort nheight;High imageUnsignedint nframenum;Frame numberUnsignedint Nframelen;Current frame data sizeUnsignedint Ntimestamphigh;//timestamp high 32-bit unsigned int ntimestamplow; //timestamp low 32-bit unsigned int nresulttype; //output message type // According to the message type corresponds to different structure body unsigned Char Chresult[mv_sc_max_result_size]; unsigned int nReserved[< Span class= "DV" >8]; //reserved}mv_sc_image_out_info
C # code
///<summary>Get photos taken by the camera///</summary>///<param name= "Handle" ></param>///<returns></returns> [DllImport ("MvSmartCamCtrl.dll")]PublicStaticexternIntMv_sc_getoneframe (INTPTR handle, byte[] pData,int Ndatasize,Out Mv_sc_image_out_info Pstdevinfo);Output frame information [StructLayout (layoutkind.sequential)]Publicstruct Mv_sc_image_out_info {PublicShort nwidth;Image widthPublicShort nheight;High imagePublicint nframenum;Frame numberpublic int Nframelen; //current frame data size public int Ntimestamphigh; //timestamp high 32-bit public int Ntimestamplow; //timestamp low 32-bit public int NResultType ; //output message type //corresponds to different structure based on message type [MarshalAs ( UnmanagedType.ByValTStr, SizeConst = 1024 * 16)] public mv_sc_result_bcr Chresult; [MarshalAs (UnmanagedType.ByValArray, SizeConst = 8)] public Span class= "Hljs-keyword" >int[] nreserved; }
So we put this DLL in the root of the program, we can implement the DLL method call.
Back to directory C # calling Java methods
IKVM. NET is a Java implementation for the mono and Microsoft. NET Framework, designed to run Java programs on the. NET platform. It contains the following components: using the. NET implementation of Java virtual machines, Java class libraries. NET implementation.
Committed in Java and. NET and the tools for interacting between
Program Requirements
We have a Java-written demo, the parameters are compressed with gzip upload 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;PublicClass demo{Public StaticStringDopostclient(string json, string URL) {HttpClient HttpClient =NewHttpClient (); String Rval =""; Postmethod Postmethod =NewPostmethod (URL);try {Gson Gson =NewGson (); InputStream in =New Bytearrayinputstream (Objecttobyte (JSON)); Postmethod.Setrequestbody (in); Httpclientparams params =NewHttpclientparams (); 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; }PublicStaticByte[]Objecttobyte (java.Lang.Object obj) {byte[] bytes =Null ObjectOutputStream oo =Nulltry {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.Printstacktrace (); } } }return bytes; }PrivateStatic java.Lang.Object Bytetoobject(Byte[] bytes) {String obj =""; ObjectInputStream Oi =Nulltry {bytearrayinputstream bi =New Bytearrayinputstream (bytes); Gzipinputstream Gzipi =New Gzipinputstream (BI); BufferedReader BufferedReader =New BufferedReader (new inputstreamreader (Gzipi, "UTF-8")); String Line; while (line = Bufferedreader.null) {obj+=line;}} catch (Exception e) {e.printstacktrace ();} finally {if (Oi! = < Span class= "Hljs-keyword" >null) {try {oi.catch (IOException e) {e.printstacktrace ();}}} return obj;}
This code I use C # rewrite, with HttpWebRequest way to the server, the server over gzip decompression, check the reason is because Java and C # byte type value range, we have two solutions, One is to make this Java webservice hanging on the server, C # again to call, the second is to compile this method can be directly called by C # DLL, because this method function relatively single, we chose the latter.
Environment configuration
Ikvm.net Download and extract the data from the Bin folder for the jar package conversion and the underlying DLL.
IKVM. OpenJDK.ClassLibrary.dll for C # program Access.
: https://yunpan.cn/cBHTS5fXsIe9v access password 0847.
Add the address of the Ikvm.net Bin folder to the environment variable.
Computer Right-click Properties-Advanced system Settings-advanced-environment variables--find path--in System variables add the address of the Bin folder,
Entering IKVMC in CMD has a help document stating that the environment is configured successfully.
Ikvm.openjdk.core.dll,ikvm.runtime.dll,ikvm.runtime.jni.dll and IKVM.OpenJDK.ClassLibrary.dll are public DLLs under the Bin folder, and all converters need to reference
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
Let's start by generating the Gson-2.4.jar,commons-logging-1.1.3.jar,commons-codec-1.6.jar DLL with the following syntax:
IKVMC the physical path of the jar package.
Win7 system is generated by default under C:\Users\Administrator this folder
The commons-httpclient-3.1.dll generates the following syntax:
Ikvmc Commons-httpclient-3.1.jar-r:commons-logging-1.1.3.dll-r:commons-codec-1.6.dll
The JavaApi.dll generated syntax for the Demo package named Javaapi.demo is as follows:
Ikvmc Javaapi.demo.jar-r:commons-httpclient-3.1.dll-r:gson-2.4.dll
The above files are relative to the physical path, and then all the generated DLLs are added to the C # project reference, including the previous public DLLs, referenced to all referenced DLLs in the project
This allows you to use this Java method directly in your program.
Demo.Demo.doPostClient (JS, url);
The package name in the first demo Java program.
The class name in the second demo Java program.
C # Calling Java methods (verbose instance)