Pass an array of integers from C to Java with JNI
Hello,
I have a C function that returns a struct me. The fields of this struct are all of type integer. I, with the fields of this structure create an array of integers in C language I would like to pass this array of integers c, in Java using JNI.
How can I make this?
I don't see how you compiled that.
It certainly will not compile for me.
jintArray position=(jintArray)(*env)->NewIntArray(env,2);That is the invocation idiom for C code.
jint f[2];You cannot have a variable declaration in the middle of a method (block) in C code. That is only allowed in C++.
C code and C++ code is not the same.
The following is C++ code. Note that it does NOT include getBinaryPoint() since that method could be the source of the problem.
jintArray position = env->NewIntArray(2);
if(position==NULL) return NULL;
jint f[2];
f[0]=3;
f[1]=4;
env->SetIntArrayRegion(position,0,2,f);
return position;
Similar Messages
-
Pass an ArrayList of objects from C++ to JAVA using JNI
Hello,
I need to get the running Windows processes using C++ and have a Process struct in C++ having 2 fields: name and pid. I want to pass an ArrayList of Process from C++ to Java. I have found an example of how to pass an array of objects from C++ to Java, but I'd like to pass an ArrayList, and I was wondering if this is possible, before understanding that example and use an array.
I don't have much experience with C++ and I don't even know if you have something like an ArrayList in C++, so I'm sorry if it doesn't make any sense what I'm talking about. Thank you.From C you can access and/or imnstantiate one of the
java collections. In other words, your C code should
simply populate java structures and a collection.I have read this is possible after I posted this, but didn't find an example yet. I began reading "Java Native Interface" book from Addison-Wesley today to get a better understanding of JNI.
If you know where to find an example of doing this, I would appreciate it. Otherwise, I suppose I will find this in the above mentioned book quite soon... Thank you. -
How to return a char [][] from c++ to java with JNI
hi , i am new to JNI and i am having some troubles with a special task :
in fact i am supposed to treat some data stored in a char[100][100] value and then return the result to java , the result is the sam value bur modified i mean a char [100][100] variable too...
i saw that we can rely on
JNIEXPORT jobjectArray JNICALL Java_JNITest_newArray (JNIEnv *env, jclass, jint size )
jobjectArray joa = ... ); // what in my case ?;
jsize len1 = (jsize)env->GetArrayLength(joa);
for (int i=0; i<l en1; i++)
jintArray colonne = (jintArray)env->GetObjectArrayElement(joa, i);
jsize len2 = (jsize)env->GetArrayLength(colonne);
jint *element = env->GetIntArrayElements(colonne, 0);
for(int j=0; j<len2; j++)
jint res = element[j];
// process some treatment here
// how now to return the result to java : joa modified !!
[/code]
may be some errors present in this piece of code ...but i rely on your help to have the solution!! please i am really desperated !You know that any JNI function for an array handles or creats only one-dimensional array. But if you know Java array structure then with these functions you can create Java arrays of any dimensions.
A Java multi-dimensional array is a set of nested one-dimensional arrays (consider dimensions from left to right). I give you only schema of this process. Let create the array of your type (for example, char [2][3]):
1) create one-dimensional object array "[C"[/b] of size two for the first dimension (and assign it to some variable of type jobjectArray) ;
2) create two three-dimentional char arrays and assign these local references to each element of the array created in prev. step;
3) fill each array created in (2) with your data (characters);
4) return to Java code the reference created in the step (1) and do not delete local references created in steps (1) and (2). -
Passing an array as parameter from java (java controls) to stored procedure
Hi,
I'm using java controls (BEA Weblogic Workshop 8.1) to call a stored procedure and send an array as a parameter to the stored procedure from java. The following code below throws an exception "Fail to convert to internal representation".
Java code
import com.bea.control.DatabaseControl.SQLParameter;
// Here i create the java array
int[] javaArray={12,13,14};
//The code below is used to create the oracle sql array for the procedure
SQLParameter[] params = new SQLParameter[1];
Object obj0=javaArray;
params[0] = new SQLParameter(obj0, oracle.jdbc.OracleTypes.ARRAY, SQLParameter.IN);
// the code below calls the testFunc method in OJDBCtrl.jcx file
String succ= dbControl.testFunc(params);
OJDBCtrl.jcx
* @jc:sql statement="call CMNT_TST_PROC(?))"
String testFunc(SQLParameter[] param);
The stored procedure used:
TYPE SL_tab IS TABLE OF number INDEX BY PLS_INTEGER;
Procedure cmnt_tst_proc (cmnt_tst sl_tab);
Procedure cmnt_tst_proc (cmnt_tst sl_tab) is
BEGIN
dbms_output.put_line('Hello');
END;
I am getting the following exception
Failure=java.sql.SQLException: Fail to convert to internal representation: [I@438af4 [ServiceException]>
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:125)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:162)
at oracle.jdbc.driver.DatabaseError.check_error(DatabaseError.java:861)
at oracle.sql.ARRAY.toARRAY(ARRAY.java:210)
at oracle.jdbc.driver.OraclePreparedStatement.setObjectCritical(OraclePreparedStatement.java:7768)
at oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:7449)
at oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:7837)
at oracle.jdbc.driver.OracleCallableStatement.setObject(OracleCallableStatement.java:4587)
at weblogic.jdbc.wrapper.PreparedStatement.setObject(PreparedStatement.java:244)
at com.bea.wlw.runtime.core.control.DatabaseControlImpl._setParameter(DatabaseControlImpl.jcs:1886)
at com.bea.wlw.runtime.core.control.DatabaseControlImpl.getStatement_v2(DatabaseControlImpl.jcs:1732)
at com.bea.wlw.runtime.core.control.DatabaseControlImpl.invoke(DatabaseControlImpl.jcs:2591)
at com.bea.wlw.runtime.core.dispatcher.DispMethod.invoke(DispMethod.java:377)
at com.bea.wlw.runtime.core.container.Invocable.invoke(Invocable.java:433)
at com.bea.wlw.runtime.core.container.Invocable.invoke(Invocable.java:406)
at com.bea.wlw.runtime.core.container.Invocable.invoke(Invocable.java:249)
at com.bea.wlw.runtime.jcs.container.JcsContainer.invoke(JcsContainer.java:85)
at com.bea.wlw.runtime.core.bean.BaseContainerBean.invokeBase(BaseContainerBean.java:224)
at com.bea.wlw.runtime.core.bean.SLSBContainerBean.invoke(SLSBContainerBean.java:109)
at com.bea.wlwgen.StatelessContainer_ly05hg_ELOImpl.invoke(StatelessContainer_ly05hg_ELOImpl.java:153)
Can you please let me know, what i'm doing wrong and how i can pass an array to a procedure/function using java controls.
Any help will be highly appreciated.
Edited by: user12671762 on Feb 24, 2010 5:03 AM
Edited by: user9211663 on Feb 24, 2010 9:04 PMThanks Michael.
Here's the final code that i used, this might be helpful for those who face this problem
Java Code
// Following code gets the connection object
InitialContext ctx = new InitialContext();
dataSource = (DataSource)ctx.lookup("<DataSourceName>");
conn=dataSource.getConnection();
// Following code is used to create the array type from java
String query="CREATE OR REPLACE TYPE STR_ARRAY AS VARRAY(3) OF NUMBER";
dbControl.runTypeQuery(query);
// Following code is used to obtain the oracle sql array as SQLParameter
ArrayDescriptor desc = ArrayDescriptor.createDescriptor("<schemaName>.STR_ARRAY", conn);
Object[] elements = new Object[3];
elements[0] = new Integer(12);
elements[1] = new Integer(13);
elements[2] = new Integer(14);
oracle.sql.ARRAY newArray = new oracle.sql.ARRAY( desc, conn, elements);
SQLParameter[] params = new SQLParameter[1];
params[0] = new SQLParameter(newArray, oracle.jdbc.OracleTypes.ARRAY, SQLParameter.IN);
String succ= dbControl.testFunc(params); -
Can i return an Array of Objects from c++ to java ??
hello all,
Can i return an Array of Objects from c++ to java ??
If so how is it possible ??
regards,
gautamI suggest you look into the JNI, Java Native Interface. The answer is yes.
-
Return array of varchar from oracle to java
Hi,
I am trying to return an array of varchar from database to java. However, when I print the values in java, it prints hexadecimal values like this.
0x656E7472792031
0x656E7472792032
0x656E7472792033
0x656E7472792034
I am using oracle 9.2.0.5.0 and jdk 1.4
This happens only when the NLS character set of the database is WE8MSWIN1252 (default character set).
It works fine on databases with UTF8 and US7ASCII character sets.
Any leads to the reason behind this behaviour is greatly aprpeciated.
Here's the code snippet...
<code>
//USER DEFINED TYPE
create or replace type SimpleArray
as table of varchar2(30)
</code>
<code>
// FUNCTION RETURNING USER DEFINED TYPE
create or replace function getSimpleArray return SimpleArray
as
l_data simpleArray := simpleArray();
begin
for i in 1 .. 10 loop
l_data.extend;
l_data(l_data.count) := 'entry ' || i;
end loop;
return l_data;
end;
</code>
<code>
// JAVA METHOD
public static void main(String[] args)
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:db1252";
Connection conn = DriverManager.getConnection(url, "ring", "ring");
CallableStatement stmt = conn.prepareCall("{? = call "
+ "getSimpleArray" + "}");
Array rs = null;
ResultSet rsltSet = null;
stmt.registerOutParameter(1, Types.ARRAY, "SIMPLEARRAY");
stmt.execute();
rs = stmt.getArray(1);
String[] values = (String[]) rs.getArray();
System.out.println(rs.getBaseTypeName());
System.out.println(values.length);
for (int i = 0; i < values.length; i++) {
System.out.println(values);
rsltSet = rs.getResultSet();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
</code>
Thanks,
VivekActually, check nls_charset12.zip. It looks like 9.2.0.5 driver contains only the *.zip version. Make sure that the file exists in the directory pointed by the CLASSPATH. Use full path, do not use %ORACLE_HOME%.
I have reproduced your problem without nls_charset12.zip and I could not reproduce it with the file in the class path. Double-check how classpath is set in your environment. Maybe it is overriden by some configuration or batch file.
-- Sergiusz -
Passing an array of integers to a method...
here's the case, i have 2 array of integers parent and child. how can i pass the arrays in a method so i can evaluate the contents of both arrays?
here's the block of the code that contains what i'm talking about.
for(int i=0; i<tree.length; i++) {//separate child from parent
int[] parent = new int[(tree.length()/2)];
int[] child = new int[(tree[i].length()/2)];
for(int j=0, ctr=0; j<tree[i].length(); j++, ctr++) {
parent[ctr] = Integer.parseInt(Character.toString(tree[i].charAt(j))); //get the parents
j++;
child[ctr] = Integer.parseInt(Character.toString(tree[i].charAt(j))); //get the children
if(isTree(parent, child)) //evaluate if case is a tree
System.out.println("Is a tree");
else
System.out.println("Is not a tree");
}//separate child fronm parentgeez, thanks... adding "static" did work.. >_< my bad, i'm new in java... and i'm sorry for calling you
"sir", thanks a lot monica... ^^ by the way, it's 1:00 pm here asia.I'm glad it worked--do you understand what "static" means here?
No problem about the "sir". I usually use "he" myself, if I don't know whether it should be he/she. And, around here on the forum (and software engineers at most companies), there are certainly more men than women. People tend to look at MLRon and assume my name is "Ron", but that's my last name. :)
You don't need to call people "sir" or "ma'am" here. Just names or screen names (like MLRon) will do. :)
Have a nice afternoon, then! -
Using An Array Collection Produced From XML In Conjunction With Shared Object
I have an old app that Greg LaFrance helped me out with greatly which allows the user to drag items between two tilelists and then save the contents of both tilelists by clicking a save button using the sharedObject method. The tilelists are populated by array collections defined in the app. I want to change this so that the tilelists are instead populated by an array collection which I've retrieved from a remote xml file via http request but I can't get this to work. Basically I need to replace both the predefined array collections profile1NewsAndSportaddLinksFullAC and profile1NewsAndSportaddLinksAC with my xml/httprequest produced newsAC array collection and still make the tilelists saveable. Can anyone help me out? Here's the code:-
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication
xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="newsService.send(); initprofile1NewsAndSportSO()">
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
import mx.collections.*;
import flash.net.SharedObject;
Bindable]
private var newsAC:ArrayCollection;
private function newsResultHandler(event:ResultEvent):void{
newsAC=newsService.lastResult.newscategory.news;
public var profile1NewsAndSportSO:SharedObject;
private var profile1NewsAndSportaddLinksFullAC:ArrayCollection = new ArrayCollection([{label:
"BBC News"},{label:
"ITV"},{label:
"Sky News"}]);
private var profile1NewsAndSportaddLinksAC:ArrayCollection = new ArrayCollection([{label:
"BBC News"},{label:
"ITV"},{label:
"Sky News"}]);
private function profile1NewsAndSportReset():void{resetprofile1NewsAndSportAC();
profile1NewsAndSportAddLinksTilelist.dataProvider
= profile1NewsAndSportaddLinksAC;
profile1NewsAndSportLinkChoice.dataProvider =
new ArrayCollection([]); }
private function resetprofile1NewsAndSportAC():void{profile1NewsAndSportaddLinksAC.removeAll();
for each(var obj:Object in profile1NewsAndSportaddLinksFullAC){profile1NewsAndSportaddLinksAC.addItem(obj);
private function initprofile1NewsAndSportSO():void{profile1NewsAndSportSO = SharedObject.getLocal(
"profile1NewsAndSport");
if(profile1NewsAndSportSO.size > 0){
if(profile1NewsAndSportSO.data.profile1NewsAndSportaddList){
if(profile1NewsAndSportSO.data.profile1NewsAndSportaddList != "empty"){
var profile1NewsAndSportaddList:Array = profile1NewsAndSportSO.data.profile1NewsAndSportaddList.split(",");
var profile1NewsAndSporttempAC1:ArrayCollection = new ArrayCollection();
for each(var str:String in profile1NewsAndSportaddList){
for each(var obj1:Object in profile1NewsAndSportaddLinksAC){
if(str == obj1.label){profile1NewsAndSporttempAC1.addItem(obj1);
continue;}
if(profile1NewsAndSporttempAC1.length > 0){profile1NewsAndSportAddLinksTilelist.dataProvider = profile1NewsAndSporttempAC1;
if(profile1NewsAndSportSO.data.profile1NewsAndSportchoiceList){
var profile1NewsAndSportchoiceList:Array = profile1NewsAndSportSO.data.profile1NewsAndSportchoiceList.split(",");
var profile1NewsAndSporttempAC2:ArrayCollection = new ArrayCollection();
for each(var str2:String in profile1NewsAndSportchoiceList){
for each(var obj2:Object in profile1NewsAndSportaddLinksAC){
if(str2 == obj2.label){profile1NewsAndSporttempAC2.addItem(obj2);
continue;}
if(profile1NewsAndSporttempAC2.length > 0){profile1NewsAndSportLinkChoice.dataProvider = profile1NewsAndSporttempAC2;
else{profile1NewsAndSportReset();
private function saveprofile1NewsAndSport(event:MouseEvent):void{
var profile1NewsAndSportaddList:String = "";
if(profile1NewsAndSportAddLinksTilelist.dataProvider){
if(ArrayCollection(profile1NewsAndSportAddLinksTilelist.dataProvider).length > 0){
for each(var obj1:Object in profile1NewsAndSportAddLinksTilelist.dataProvider){
profile1NewsAndSportaddList += obj1.label +
else{profile1NewsAndSportaddList =
"empty";}
profile1NewsAndSportSO.data.profile1NewsAndSportaddList = profile1NewsAndSportaddList;
var profile1NewsAndSportchoiceList:String = "";
for each(var obj2:Object in profile1NewsAndSportLinkChoice.dataProvider){
profile1NewsAndSportchoiceList += obj2.label +
profile1NewsAndSportSO.data.profile1NewsAndSportchoiceList = profile1NewsAndSportchoiceList;
profile1NewsAndSportSO.flush();
]]>
</mx:Script>
<mx:HTTPService id="newsService" resultFormat="object" result="newsResultHandler(event)" url="http://www.coolvisiontest.com/getnews.php"/>
<mx:Button click="profile1NewsAndSportReset()" id="reset" label="
Reset" y="5" height="25" x="5"/>
<mx:TileList id="profile1NewsAndSportLinkChoice" fontWeight="bold" dragEnabled="
true" dragMoveEnabled="true" dropEnabled="true" height="129" width="
650" top="5" left="521" columnCount="5" rowHeight="145" columnWidth="
125" backgroundColor="#000000" color="#FFFFFF"/>
<mx:TileList id="profile1NewsAndSportAddLinksTilelist" fontWeight="bold" dragEnabled="
true" dragMoveEnabled="true" dropEnabled="true" height="129" width="
385" top="5" left="128" columnCount="3" rowHeight="145" columnWidth="125" backgroundColor="
#000000" color="#FFFFFF"/>
<mx:Button click="saveprofile1NewsAndSport(event)" id="save" label="Save Changes" x="
5" y="38" width="113" height="25.5"/>
</mx:WindowedApplication>It might be easy to solve these issues if you post your form.
Post your form if it doesn't contain any confidential information.
Nith -
Transfer a Jpeg From Delphi to Java via JNI?
Hi Guys,
I am currently working on a project in which I have Windows DLL code that takes a screen capture (I'm using Delphi to write this). The result of this capture is stored as a TJpegImage. I have my Delphi code hooked to Java code (which the main program is written in) via JNI. I am trynig to transfer the Jpeg in a format in which Java can easily take it and make a BufferedImage out of it. How can I go about this? I have a few ideas, but I want to do it in the most efficient way possible. If someone knows how to do this, can they please share the solution with me?
Thanks,
-Tonywhome0,
Yes, thanks, that's exactly what I've been using. Basically, I'm at the point now where I know how to transfer the bytes, but for some reason, when I do this on the Java end:
ByteArrayInputStream input = new ByteArrayInputStream( byteArr );
JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder( input );
BufferedImage bi = decoder.decodeAsBufferedImage();
I get this error:
com.sun.image.codec.jpeg.ImageFormatException: Not a JPEG file: starts with 0x60 0x23
at sun.awt.image.codec.JPEGImageDecoderImpl.readJPEGStream(Native Method)
at sun.awt.image.codec.JPEGImageDecoderImpl.decodeAsBufferedImage(Unknown Source)
at com.sun.media.protocol.screen.LiveStream.read(LiveStream.java:166)
at com.sun.media.parser.RawBufferParser$FrameTrack.transferData(RawBufferParser.java:725)
at com.sun.media.protocol.screen.LiveStream.run(LiveStream.java:235)
at java.lang.Thread.run(Unknown Source)
I am baffled at this point, because I do a byte count before I send from my Delphi code, and a byte count on the Java receiving end, and they are identical. Looking at other JPGs I have on my hard drive, they begin in the same manner that this file does. So I'm not sure what's going on here.
-Tony -
Passing array of values from front panel to menu
I am working with a group programming a multichannel current stimulation device and we are currently having trouble setting up the run time menu. The burning question that we have is trying to figure out how to pass an array of values from the front panel to the menu that we are setting up in the block diagram, any advice?
Thank youTake a look at this. Its just a simple menu update using a for loop. Uses whatever your values are as the item tag and item names. Remember, item tags need to be unique. This specifically goes under the sub menu of channel, which has to be created before.
Attachments:
menu.vi 12 KB -
I'm having trouble passing an array of integers to a string and vice versa i.e. the array has
element[0] =1
element[1] =0
element[2] =0 but it can hold up to 16 elements
what I want is for this array which holds a binary number represented by ints to be represented as the string "001". Im passing the method an array then I want it to loop the length of the array and store each element as a part of the string. I then want to add the number to another number put it back in an array and return it. If anyone has any help I would appreciate it.
Thanks.public class YourClass {
public static String arrayToString(int[] theArray) {
int lim = theArray.length;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < lim; i++) {
sb.append(String.valueOf(theArray));
return sb.toString();
public static int[] stringToArray(String theString) {
int lim = theString.length();
int[] theArray = new int[lim];
for (int i = 0; i < lim; i++) {
theArray[i] = Integer.parseInt(theString.substring(i, i+1));
return theArray;
public static void main(String[] args) {
int[] theArray = {1,0,0,1,1};
String theString = arrayToString(theArray);
System.out.println(theString);
int[] theArray2 = stringToArray(theString);
System.out.println(arrayToString(theArray2)); -
Passing an array of objects.
I have been trying to pass an array of objects from java to C. They are simple objects, only fields, no methods.
Example...
class User
String name;
int id;
public class JNIExample
User[] users = new User[10];
public native void nativeCode(User[] usersarray);
static
try{
System.loadLibrary("object");
}catch(Exception e)
System.out.println("Could not load library.");
public static void main(String[] args)
JNIExample anex = new JNIExample();
anex.nativeCode(anex.users);
Could someone give me sample code on how to access the array elements and get/set the object values on the C side. In the above code I did not create any of the objects in the array or set their field values but these will be set on the java side.
Any help would be greatly appr.
Thanks,
DarrinJNIEXPORT void JNICALL Java_User_nativeCode
(JNIEnv *env, jobject this, jobjectArray arr) {
jsize idx; // array index
// accessing the Users
for(idx = env->GetArrayLength(env, arr); idx-- > 0;) {
jobject user = env->GetObjectArrayElement(env, arr, idx);
// do something with it
// setting the Users
for(idx = env->GetArrayLength(env, arr); idx-- > 0;) {
jobject user = ...
env->SetObjectArrayElement(env, arr, idx, user);
} -
Functions to read and display an array of integers
Hi guys,
I am trying to implement with a class called Sort a function to read in an array of integers from a file and a function to display that array.
public class Sort
public static int[] read(String file) throws IOException
/* Create Reader object to read contents of file */
BufferedReader br = new BufferedReader(new FileReader(file));
/* Read file and store lines in ArrayList */
ArrayList<Integer> list = new ArrayList<Integer>();
/* Variable */
String in;
/* While not equal to null reads data from file */
while ((in = br.readLine()) != null)
/* Adds data from file to ArrayList */
list.add(Integer.parseInt(in));
/* Converts ArrayList into an array */
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++)
/* Get array elements */
array[i] = list.get(i);
/* Returns array */
return array;
public int display()
for (int i = 0; i < list.size(); i++)
System.out.println(list.get(i));
}I am having one of those moments when you forget everything, I need help with display the array in a seperate function, will someone help me please?
Thanks!I know that its just implementing it.
I have:
public void display()
for(int i = 0; i < array.length; i++)
System.out.println(array);
But I'm lost on how to make this work, i.e it says "cannot find array variable". I've not done Java for a while and feel like I have forgot everything!
Edited by: mbruce10 on Nov 15, 2009 1:31 AM -
Integerating objective c with java through JNI in MAC
Hi,
I hv some code in objective c and i hv to call some methods from java code. So i want to use JNI interface for that.
Could any body give me refrence on how to go about it. I know little bit about integerating c code and java thorugh jni on windows.
Thanks in advace.
Regards,
Prashantyou need to create dll using vc++ or Borland compiler
i will try to help you out.
//mac.java
class mac
public native void getMac();
private native String getLine(String prompt);
static {
System.loadLibrary("myMac");//This is myMac.DLL
/*if generated by borland
System.loadLibrary("mymac");//This is mymac.dll
public static void main(String[] args)
mac mc=new mac();
String input = mc.getLine("Enter Some Thing ");
System.out.println("You Entered " + input);
System.out.println(mc.getMac());
}prompt> javac mac.java
prompt> javah -jni mac
Borland compiler
/*mymac.c*/
#include <jni.h>
#include "mac.h"
#include <stdio.h>
JNIEXPORT void JNICALL
Java_mac_getMac(JNIEnv *env, jobject obj)
printf("I am in getmac dir in mymac.dll (Borland) \n");
return;
JNIEXPORT jstring JNICALL
Java_mac_getLine(JNIEnv *env, jobject obj, jstring enter)
char buf[128];
const char *str = (*env)->GetStringUTFChars(env, enter, 0);
printf("%s", str);
(*env)->ReleaseStringUTFChars(env, enter, str);
scanf("%s", buf);
return (*env)->NewStringUTF(env, buf);
}To generate DLL
create bcc32.cfg file in %BORLAND_INSTALL%/BCC5/bin Folder
In the bcc32.cfg file add following code
-I"%BORLAND_INSTALL%\BCC55\include;%JAVA_HOME%\include;%JAVA_HOME%\include\win32"
-L"%BORLAND_INSTALL%\BCC55\lib;%BORLAND_INSTALL%\BCC55\Lib\PSDK;"
i.e the path for borland compiler and java.
now goto prompt and say
prompt>bcc32 -tWM -tWD mymac.c
This will create mymac.lib File
Now say
prompt>implib -c mymac.lib mymac.dll
That's it!!
there you are with dll
Now you can run the mac.class file by using java
VC++
Click File->New->Win32Dynamic-Link Library
Give name and Select
A simple DLL project
You will have
myMac.CPP file
// myMac.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include "mac.h"
#include "jni.h" //can copy or give full path
#include <math.h>
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
return TRUE;
JNIEXPORT void JNICALL
Java_mac_getMac(JNIEnv *env, jobject obj)
printf("You are in getMac (VC++) DLL\n");
JNIEXPORT jstring JNICALL
Java_mac_getLine(JNIEnv *env, jobject obj, jstring enter)
char buf[128];
const char *str = env->GetStringUTFChars(enter, 0);
printf("\n%s", str);
env->ReleaseStringUTFChars(enter, str);
scanf("%s", buf);
return env->NewStringUTF(buf);
}Hope this is useful
regards
kanad Deshpande -
Need help on passing an array to java routine from PL/SQL
I got a math routine in java and the idea is have an array of integer and the java routine does some computatoin and then pass the array back to pl/sql
and I google the web most code is calling pl/sql from java but not the other way round. any help will be really appreciated.
{code}
package tst;
import java.util.*;
public class plsql3 {
private final static int factor1 = 2;
public static void getFib2(int[] in, int[] out, int k){
for (int i=0;i<=k-1;i++){
out[i]= in[i] * factor1;
public static void main(String[] arg){
int[] in2 = {1,2,3,4,5};
int[] out2= {0,0,0,0,0};
getFib2(in2,out2,2);
for ( int j = 0 ; j <= out2.length-1;j++) {
System.out.println(out2[j]);
{code}
{code}
CREATE or replace PROCEDURE getfib5 (x IN OUT numlist, y IN OUT numlist, k in number)
AS LANGUAGE JAVA
NAME 'tst.plsql3.getFib2(int[], int[],int)';
set serveroutput on format wraped;
declare
in2 numlist := numlist(1,2,3,4,5,6);
out2 numlist := numlist(0,0,0,0,0,0);
begin
--in2(0) := 1;
--in2(1) := 2;
--in2(2) := 3 ;
for i in 1..in2.count
loop
dbms_output.put_line(in2(i));
end loop;
for i in 1..in2.count
loop
dbms_output.put_line(out2(i));
end loop;
getFib5(in2,out2,2);
for i in 1..in2.count
loop
dbms_output.put_line(in2(i));
end loop;
for i in 1..in2.count
loop
dbms_output.put_line(out2(i));
end loop;
--dbms_output.put_line(in2.count);
end;
{code}
{code}
javac -source 1.5 -target 1.5 tst/plsql3.java
{code}
Error report:
ORA-00932: inconsistent datatypes: expected a value at argument position 1 that is convertible to a Java int got an Oracle named TYPE (ADT, REF etc)
ORA-06512: at "TK1.GETFIB5", line 1
ORA-06512: at line 18
00932. 00000 - "inconsistent datatypes: expected %s got %s"
*Cause:
*Action:http://asktom.oracle.com/pls/asktom/f?p=100:11:::::P11_QUESTION_ID:3696816290928
Maybe you are looking for
-
How can I do Streaming Video from a Mac Pro
I want to set up a small family web site and run streaming video off my Mac Pro. Do I need to have OS X server to do this? Can I run OS X applications like Final Cut Express on OS X server?
-
Image open problem in nokia 5230
Dear All, I have nokia 5230 mobile & i am using from last 10 months but from past few days i am facing problem regarding image/songs open problem. whenever i trying to open image my phone gets hang & it shows nothing in it but i have 100 pics in mem
-
How to get tools and other bars back in view after deleting show-bar?
How to get tools and other bars back in view after deleting show-bar?
-
I used an AOL name several years but have been using a .mac for at least three years. Do I need to do anything?
-
Why doesn't my ear plugs from my ipod work on the iphone ? ... actually none of my 3rd party RCA plugs or head phones work either? Is different configuration due to the built in mic .? Is there a adapter that works? Thanks Mr braddyboy