Saturday, December 31, 2011

C# in java

I Like to post though it avail at code project.
for your refernce with parameter
==========================================

    public class Sum
    {
        public int add(int a, int b)
        {
            return a + b;
        }
    }
===========================================
save as Sum.cs and compile it to module
using cmd:

>csc /t:module sum.cs

Create Java File to test
===========================================
public class test{
public native int add(int a,int b);
 static {
        System.loadLibrary("JSample");
    }
   
    public static void main (String[] args) {
       System.out.println(new test().add(10,15));
    }
}
==========================================
save it as test.java compile as
>javac test.java
create native header file
>javah -jni test
it will create test.h
==========================================
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class test */

#ifndef _Included_test
#define _Included_test
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     test
 * Method:    add
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL Java_test_add
  (JNIEnv *, jobject, jint, jint);

#ifdef __cplusplus
}
#endif
#endif
==========================================

create win32 project using visual studio (I used VS2010)
Choose project name as JSample

include header and C#.net module
write header for manged C++ conversion
==============================================
#using <mscorlib.dll>
#using "Sum.netmodule"
using namespace System;
public __gc class SumC
{
public:
    Sum __gc *t;
    SumC()
    {
        t = new Sum();          
    }
    int callCSharpSum(int a,int b)
    {
        return  t->add(a,b);
    }
};
===========================================
save it as sum.h

create sum.cpp file
============================================
#include <jni.h>
#include "test.h"
#include "sum.h"

JNIEXPORT jint JNICALL Java_test_add
    (JNIEnv *, jobject, jint a, jint b)
{
    SumC* t = new SumC();  
    return t->callCSharpSum(a ,b );
}
=============================================
optimze compliler to build /clr:oldSyntax
Include Jdk/Include directory path
build the project.
we will Get JSample DLL

run the project
with C#.net module,Native DLL file and class file at the same folder.

>java test
25
================================================
Hope it helps

find the link

https://docs.google.com/open?id=0B8j-6CFq6hsGY2EzOWRmMGMtZDBjOS00NTgwLTgxYjQtMzhhODk2OWM2N2Vj


Regards
..arun@darkside..

Trace to Log File

 private readonly FileStream _obj = new FileStream("log.txt", FileMode.OpenOrCreate);

At form Load use this

  var objt = new TextWriterTraceListener(_obj);
   Trace.Listeners.Add(objt);
    Trace.AutoFlush = true;