상세 컨텐츠

본문 제목

c 그리고 자바 연동관련 dll 연동 관련

본문

반응형

 

 

=================================

=================================

=================================

 

 

 

출처: http://landsnail.tistory.com/2

[JNI] 자바로 DLL 로드 하기.

 Developer/Java 2012/11/02 14:14

자바에서는 JNI를 통하여 C코드를 사용할 수 있다.

주의 할점 경로 및 자바 헤더 파일 생성 과정

아래의 예를 들어 보자 

먼저

자바로 C 코드의 함수명을 호출할

메소드를 만든다

 

package com.test.util

public class loaddll

{

public native void a();

public native int b(String str);

public native String c(int integer);

}

여기서 주의 할점은 package 명이다.

이 패키지명은 C코드와 통신하기 위한 헤더파일을 생성시 매우 중요 하다.

자 그럼 컴파일을 해보자

자바 프로젝트가 있는 root 디렉토리 즉 src 폴더에 가서

CMD 창을 열고

 

1. javac com.test.util.loaddll.java

2. javah -jni com\test\util\loaddll

하면 클래스 파일인

loaddll.class 파일과

헤더 파일인

com_test_util_loaddll.h 이란 파일이 생성 된다

위 파일을

C 프로젝트에서 로드할 헤더에 포함시켜준다.

그리고 C프로젝트에선 jni를 이용할 수 있게

아래의 경로 처럼 include 경로를 visual c++ 디렉토리로 추가해준다.

 

 

 

 

 

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <jni.h>
#include "com_test_util_loaddll.h"

JNIEXPORT void JNICALL Java_com_test_util_loaddll_a(JNIEnv *env, jobject obj)
{
 }
JNIEXPORT jint JNICALL Java_com_test_util_loaddll_b(JNIEnv *env, jobject obj, jstring msg)
{
}
JNIEXPORT jstring JNICALL Java_com_test_util_loaddll_c(JNIEnv *env, jobject obj, jint inte)
{
}

해서 위와 같이 코드를 작성 했으면

dll을 파일 생성

한다..

 

자 이제 자바 프로젝트로 돌아가서 테스트 코드를 작성 할때 유의할점!!

package com.test;

import com.test.util.loaddll;

public class LoadDLLTest
{
    public static void main(String[] args)
    {
        loaddll module = new loaddll();

module.a();

...

..

}

 

package com.test.util;

public class loaddll

{

public native void a();

public native int b(String str);

public native String c(int integer);

public loaddll()

{

System.loadBinary("lib/loaddll");

<!-- 이거나

System.load("절대 경로 ");

}

}

 

패키지가 중요 하다. dll 헤더 파일과 동일한 패키지 에 위치한 클래스에서 로드 해야 하며.

그렇지 않을경우 경로를 찾을 수 없는다는 오류가 발생한다 .

두번째. dll명과 클래스 명은 같게 해주는 것이 좋다.

세번째 절대경로 확장자에는 c:\loaddll.dll 을 붙이지만

loadbinary 일경우에는  .dll 을 붙이지 않는다.

중요 참고 사이트

http://aploit.egloos.com/4937154 

http://code.google.com/p/theyard/source/detail?r=168

 

 

 

=================================

=================================

=================================

 

 

 

출처: http://kin.naver.com/qna/detail.nhn?d1id=1&dirId=1040201&docId=73257133&qb=7J6Q67CUIGRsbA==&enc=utf8§ion=kin&rank=1&search_sort=0&spq=0&pid=RyQPyc5Y7vssssV97kRsssssssG-006576&sid=Uyfek3JvLCIAACnqGMU

 

자바프로그램에서 다른 언어로 만들어진 라이브러리를 호출하기 위한 인터페이스로

JNI(Java Native Interface)가 있습니다.

JNI는 기본적으로 C++언어의 문법을 사용합니다만, 특수한 데이터형이나 예약어들을 사용하고

일반적인 C++과 비교할 때 차이가 나는 부분이 많습니다.

시스템 구성을 간단히 설명하면 다음과 같습니다.

자바프로그램 -> JNI로 만든 DLL -> 사용하시려는 C로 만들어진 DLL

다만, 자바에서 JNI를 호출하는 방법, JNI로 DLL을 만드는 방법등은 이해하기 어려운 내용들이 많습니다.

상세한 내용은 JNI에 관한 서적이나 자료를 찾아보시길 바랍니다.

 

 

 

=================================

=================================

=================================

 

 

 

출처:

- http://www.codeproject.com/Articles/14679/Java-NET-Integration-as-Simple-as-Possible

 

 

 

Introduction

For a number of years, I have been developing software for integrating applications written in different platforms. And in my business, I face with interoperability issues: Java and C++, Java and COM, Java and .NET. To solve them, I have developed a number of tools. The last one is the Object-Oriented JNI for .NET (low-level). This is an SDK that wraps the standard Java Native Interface for C++ in .NET classes. Playing with this tool, I have made direct embedding of .NET controls into a Java GUI.

What is Object-Oriented JNI for .NET?

The main idea of Object-Oriented JNI (OOJNI) for .NET is to expose the standard Java Native Interface SDK to .NET programmers as a set of classes. For this, I wrapped all JNI reference types, like jobject, jstring, jclass, etc., with classes:

  • JObject wraps the jobject reference,
  • JString keeps the jstring reference and makes all default string conversions Java/.NET and .NET/Java,
  • JWeakReference wraps the jweak type,
  • JClass for the jclass reference,
  • Java array classes for all primitive Java types and objects. These classes support easy access to Java array items, and can handle and create multi-dimensional Java arrays.

Most standard JNI functions are represented in a managed class ObjectOrientedJNI.JNINativeMethod as static methods. This SDK is compatible with JNI for JDK 1.3.x. The OOJNI SDK also includes a number of useful helpers for easy JNI coding in .NET. All SDK is packed into one module: OOJNIDOTNET.DLL. It is loaded first in a Java process, with the System.load(...) or the System.loadLibrary(...) methods.

An example of direct embedding of .NET contols into a Java GUI

1. Writing Java code for OOJNI

The class MainFrame creates a SWING Frame Window with the FrameWindow object, which is used as a container for the .NET UserControl object and JButton which closes the application. To activate OOJNI in Java, the application loads the module OOJNIDOTNET.DLL first, then the other JNI modules can be loaded (.NET module CSharpInJava.DLL).

 Collapse | Copy Code

import java.awt.BorderLayout; import java.awt.Color; import javax.swing.JButton; import javax.swing.JFrame; public class MainFrame extends JFrame { static{ System.loadLibrary("oojnidotnet"); System.loadLibrary("CSharpInJava"); } FrameWindow canvas; JButton okButton; public MainFrame() { super("qwerty"); initialize(); } public void initialize(){ okButton = new JButton(); okButton.setText("Close"); getContentPane().setLayout(new BorderLayout()); getContentPane().add(canvas = new FrameWindow(), BorderLayout.CENTER); getContentPane().add(okButton, BorderLayout.SOUTH); canvas.setBackground(Color.blue); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { System.exit(0); } }); okButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { System.exit(0); } }); pack(); setSize(200, 200); } public static void main(String args[]) { new MainFrame().setVisible(true); } }

The Java class FrameWindow is used as a container for the .NET UserControl object:

 Collapse | Copy Code

import java.awt.Canvas; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; public class FrameWindow extends Canvas { int ref = 0; //Called by JVM to create Canvas' Peer public void addNotify() { super.addNotify(); ref = create(); } //Called by JVM to destroy Canvas' Peer public void removeNotify() { dispose(ref); super.removeNotify(); } //Creates .NET UserControl object and //returns the reference to it native int create(); //Destroys .NET object by ref value native void dispose(int ref); }

This class keeps a reference to the .NET container object created and the two native methods implemented inCSharpInJava.DLL:

  • create - creates a .NET UserControl object in FrameWindow on an addNotify call,
  • dispose - destroys .NET objects in FrameWindow on a removeNotify call.

2. Implementing Java native methods in .NET JNI code

Java native methods can be implemented in .NET code in any class and namespace. The only restrictions are:

  • these methods should be static,
  • their names must be the same as generated with the javah.exe tool,
  • all pointer types (like JNIEnv*, jobject, jstring, jweak, jclass, etc.) should be substituted with int.

 Collapse | Copy Code

using System; using ObjectOrientedJNI; using System.Windows.Forms; namespace CSharpInJava { public class NativeJavaMethods { // Creates .NET UserControl object in Canvas static int Java_FrameWindow_create(int env, int obj) { // Check if the current thread was attached to JNI if(!JNIEnvHelper.isInitialized()) // Attach the current thread JNIEnvHelper.init(env); // Create .NET MyEmbeddedFrame in Canvas' Window MyEmbeddedFrame embeddedWindow = new MyEmbeddedFrame(new JObject(obj)); // Make GlobalReference copy with // MyEmbeddedFrame object and // return it to Java code. GlobalReference gref = new GlobalReference(embeddedWindow, true ); return gref.Reference.ToInt32(); } // Destroys .NET Controls embedded // in Canvas and .NET GlobalReference static void Java_FrameWindow_dispose(int env, int obj, int peer) { ((MyEmbeddedFrame)new GlobalReference(peer, false).Object).Dispose(); } } }

3. MyEmbeddedFrame class design

MyEmbeddedFrame extends the EmbeddedFrame class from OOJNI (see, P.Foot's example), which embeds .NET controls embedded into a Java application. Add to MyEmbeddedFrame a constructor that gets a JObject instance ofCanvas:

 Collapse | Copy Code

public MyEmbeddedFrame(JObject obj) : base(o){}

Implement EmbeddedFrame's method addComponents to initialize the .NET GUI:

 Collapse | Copy Code

protected override void addComponents() { InitializeComponent(); }

In the MS Visual Studio Designer, add to MyEmbeddedFrame, Button and Editor controls (it fills theInitializeComponent method with the code you need).

Points of interest

Now having learnt how to embed .NET controls in a Java GUI, try to write code for embedding ActiveX in Java with .NET. But it is not a simple task as above.

Other resources

  • IBM, Sun JDK1.3.x and higher,
  • .NET Framework 1.1,
  • Object-Oriented JNI for .NET (low-level) is available here.

Thanks

Thanks to a friend of mine, Igor Ladnik, for giving me remarks of material significance.

History

  • 05/07/2006 - Initial version.

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

 

 

 

=================================

=================================

=================================

 

 

 

출처: http://kin.naver.com/qna/detail.nhn?d1id=1&dirId=1040101&docId=68945182&qb=7J6Q67CUIGRsbA==&enc=utf8§ion=kin&rank=2&search_sort=0&spq=0&pid=RyQPyc5Y7vssssV97kRsssssssG-006576&sid=Uyfek3JvLCIAACnqGMU

Java는 타언어로 개발된 네이티브코드의 프로그램을 이용하기 위해서

JNI(Java Native Interface) 라고 부르는 인터페이스가 존재합니다.

JNI자체는 C++문법을 기초로 하며, 윈도우의 경우는 dll, 유닉스계열은 so파일이 생성됩니다.

자바프로그램 -> JNI로 구현한 dll/so -> 타언어로 작성한 dll/so

의 형태로 호출하게 됩니다.

JNI의 개념이나 기본적인 사항에 대해서는 밑의 링크를 참조하시고

JNI를 키워드로 검색하시면 실장방법이나 샘플코드를 찾으실 수 있으리라 생각합니다.

http://java.sun.com/javase/6/docs/technotes/guides/jni/?intcmp=3169

 

 

 

=================================

=================================

=================================

 

 

반응형


관련글 더보기

댓글 영역