JString to char *
Hi,
i have a problem with the conversion of a char* to string i do not get where the mistake is in the code of the native function:
JNIEXPORT jstring JNICALL Java_Main_get_1name(JNIEnv *env, jobject jobj, jint param)
char buf = (char*)malloc(max_char);
//Call the function in fortran
strcpy(buf, Getname(param +1));
return (*env)->NewStringUTF(env, buf);
The errors which comes are:
e:\Proyecto\wrapper\wrapper.cpp(81): error C2227: el operando izquierdo de '->NewStringUTF' debe se�alar a class/struct/union
e:\Proyecto\wrapper\wrapper.cpp(81): error C2819: el tipo 'JNIEnv_' no tiene un miembro sobrecargado 'operator ->'
anyone knows why?
Yup, muchas gracias
but i have another problem: i�m passing a fortran dll a char* in order to recalculate its elements, but it is not working. Anyone knows why?
What i am doing is like follows:
SUBROUTINE GETNAME(VALUE, ARRAKY)
!MS$ATTRIBUTES DLLEXPORT,C,ALIAS:'_Getname'::GETNAME
INCLUDE 'COMMON.LVG'
INTEGER VALUE
CHARACTER(*) ARRAKY
WRITE(*,*) "The INPUT is ", ARRAKY
WRITE(*,*) "The FORTRAN is ", MOL(VALUE)
ARRAKY= TRIM(MOL(VALUE))//CHAR(0)
WRITE(*,*) "The ARRAKI is ", ARRAKY
END SUBROUTINE GETNAME
being call in the way:
extern "C" __declspec(dllexport) char* Getname(char * ,int ,int );
//string, str_length, element
JNIEXPORT jstring JNICALL Java_Main_get_1name(JNIEnv *env, jobject jobj, jint param) {
char buf = (char)malloc(80);
buf = " ";
Getname(80, buf, 80);
printf("%s",buf);
return env->NewStringUTF(buf);
but the results are like before:
The INPUT is h //???
The FORTRAN is O23H
The ARRAKI is O //?????
And as i said after leaving the fortan code, the value is not updated
Similar Messages
-
Convert jstring to char array or int array
Hi all, please help with the following code. I've tested this code with hard coded char array and it works. Now I have to get the char array from parameter "param1" which is passed from Java.
The following code compiled with error message:
error C2223: left of '->GetStringUTFChars' must point to struct/union
JNIEXPORT void JNICALL Java_DongleSet_DongleWrite(JNIEnv *env,jobject obj,jstring param1){
char HaspBuffer[500]=(char)env->GetStringUTFChars(param1,NULL);
int Service=MEMOHASP_WRITEBLOCK;
int SeedCode=300;
int LptNum=0;
int Pass1=pass1;
int Pass2=pass2;
int p1=0;
int p2=12;
int p3=0;
int p4=(int)HaspBuffer;
hasp(Service,SeedCode,LptNum,Pass1,Pass2,&p1,&p2,&p3,&p4);
I've tried this:char HaspBuffer[500]=env->GetStringUTFChars(param1,NULL);
And this:char HaspBuffer[500]=(*env)->GetStringUTFChars(param1,NULL);
All give me errors.
Please help.char * HaspBuffer=(*env)->GetStringUTFChars(param1,NULL); When writing pure C, you have to supply the JNIEnv as first arg to every JNIEnv function pointer.char * HaspBuffer=(*env)->GetStringUTFChars(env, param1, NULL);Look here: http://developer.java.sun.com/developer/onlineTraining/Programming/JDCBook/jnistring.html
-
Converting jstring to char*
Hi,
I would like to convert a jstring (which is an argument in a method) to a C++ char*. How to do that?
I think it should be something like:
JNIEXPORT void JNICALL
Java_HelloWorld_displayHelloWorld(JNIEnv* env, jobject obj, jstring str)
char* text= ???;
Thank you for your answer :-)const char * stringa = env->GetStringUTFChars(_jstringa,null);
-
Converting jstring to char in c
I'm trying to convert a jstring to const char (a pointer), but I keep getting an exception.
is there some kind of defenition I'm missing????
here's part of the code:
jmethodID methID;
jstring jstr;
const char *str;
/* Get a reference to obj2 class */
jclass cls = (*env)->GetObjectClass (env, obj2);
if (cls == NULL){
return; /*return in case the object couldn't be found */
methID = (*env)->GetMethodID (env, cls, "getPgmId", "()Ljava/lang/String;");
jstr = (jstring) (*env) -> CallCharMethod(env, obj2, methID);
if (jstr == NULL){
printf (" \nthe result String is null \n");
fflush(stdout);
return;
str = (char)(*env)->GetStringUTFChars (env, jstr, 0);your method signature shows that your method returns a string but you are using "CallCharMethod"...you should be using CallObjectMethod since a string in java is actually an object not a datatype.
this is an example of getting a jstring and converting it to a char*. i need the char* so i do a strdup and release...
jstring desc = (jstring)env->CallObjectMethod(obj, mid, failType);
if(desc == NULL){
cout << "desc == null" << endl;
return (char*)errorHandler('c', JNI_NO_METHOD);
char* cDesc = strdup(env->GetStringUTFChars(desc, 0));
env->ReleaseStringUTFChars(desc, cDesc); -
Jstring to char*, Danish characters mixed up?
How do I preserve my danish symbols, when calling a native c++ code?
Example:
setCellValue(3,1,"Some danish symbols");
the native metode in java:
public native void setCellValue(int row, int col, String value);
the jni c++ code:
JNIEXPORT void JNICALL Java_jmjexceldll_setCellValue (JNIEnv * env, jobject, jint row, jint col, jstring value)
const jchar* str=(*env).GetStringChars(value,0);
ShowMessage(str);
cell=sheet.OlePropertyGet("ActiveSheet").OlePropertyGet("Cells",row,col);
cell.OlePropertySet("Value",str);
(*env).ReleaseStringUTFChars(value,str);
Please helpI think I have an idea....I faced a similar problem when I tried to implement a NetSendMessage function. Here is my code:
Note the WCHAR buffers and the MultiByteToWideChar function calls. I think maybe you need to do something similar.
JNIEXPORT jstring JNICALL Java_Win32Native_netSendMessage(JNIEnv *env, jobject obj, jstring strUserFROM, jstring strUserTO, jstring strMessage) {
NET_API_STATUS nasRc; // Return code
const char *pszUserTO = env->GetStringUTFChars(strUserTO,0);
const char *pszUserFROM = env->GetStringUTFChars(strUserFROM,0);
const char *pszMessage = env->GetStringUTFChars(strMessage,0);
char* pszReturn;
WCHAR wszUserTo[255];
WCHAR wszUserFrom[255];
WCHAR wszMessage[255];
MultiByteToWideChar(CP_UTF8,0,pszUserTO,strlen(pszUserTO)+1,wszUserTo,sizeof(wszUserTo)/sizeof(wszUserTo[0]));
MultiByteToWideChar(CP_UTF8,0,pszUserFROM,strlen(pszUserFROM)+1,wszUserFrom,sizeof(wszUserFrom)/sizeof(wszUserFrom[0]));
MultiByteToWideChar(CP_UTF8,0,pszMessage,strlen(pszMessage)+1,wszMessage,sizeof(wszMessage)/sizeof(wszMessage[0]));
nasRc = NetMessageBufferSend(NULL, // server name (null means this machine)
(LPCWSTR)wszUserTo, // name (alias) of recipient
(LPCWSTR)wszUserFrom, // who this is from
(LPBYTE)wszMessage, // message
wcslen((LPCWSTR)wszMessage) * sizeof(WCHAR)+1);
switch(nasRc) {
case ERROR_ACCESS_DENIED:
pszReturn = "ERROR: You do not have access to the requested function.\n";
break;
case ERROR_INVALID_PARAMETER:
pszReturn = "ERROR: One of the passed parameters is invalid.\n";
break;
case ERROR_NOT_SUPPORTED:
pszReturn ="ERROR: This network request is not supported.\n";
break;
case NERR_NameNotFound:
pszReturn ="ERROR: The user name could not be found or is not logged in.";
break;
case NERR_NetworkError:
pszReturn ="ERROR: A general failure occurred in the network hardware.\n";
break;
case NERR_Success:
pszReturn = "OK: Message successfully sent!\n";
break;
default:
pszReturn = "ERROR: Unknown error\n";
env->ReleaseStringUTFChars(strUserFROM, pszUserTO);
env->ReleaseStringUTFChars(strUserTO, pszUserFROM);
env->ReleaseStringUTFChars(strMessage, pszMessage);
return env->NewStringUTF(pszReturn); -
Converting "jstring" to "char *" in VC++
Hello,
I have a native method whose input parameter is a string. I used the below lines of code to get a char *. These code i got it from the JAVA TUTORIALS only.
JNIEXPORT jint JNICALL Java_SpringDLL_createExtensionSpringDXF
(JNIEnv *env, jobject obj, jstring jsprData)
const char sprData = (env)->GetStringUTFChars(env, jsprData, 0);
printf("%s", sprData );
(*env)->ReleaseStringUTFChars(env, jsprData, sprData);
I am using VC++ Application Wizard to generate the DLL.
The error i am getting is :
SpringDLL.cpp(72) : error C2819: type 'JNIEnv_' does not have an overloaded member 'operator ->'
C:\JDK1.3\INCLUDE\jni.h(746) : see declaration of 'JNIEnv_'
SpringDLL.cpp(72) : error C2227: left of '->GetStringUTFChars' must point to class/struct/union
SpringDLL.cpp(100) : error C2819: type 'JNIEnv_' does not have an overloaded member 'operator ->'
C:\JDK1.3\INCLUDE\jni.h(746) : see declaration of 'JNIEnv_'
SpringDLL.cpp(100) : error C2227: left of '->ReleaseStringUTFChars' must point to class/struct/union
Can anybody help me out how to get rid of this error. Please its an very urgent....
if you can send me an email then please don't hesitate to send it to "[email protected]".
Thanks,
PatroThe code from the tutorials id for C not C++. As you are using C++, use 'env' like this
jclass cls=env->GetObjectClass(obj);because when using C++ env is a pointer to an object. -
Problem in converting char * to java objects
Hi All,
When I am trying to compile the following JNI code, I am getting the under-mentioned errors.
<code>
JNIEXPORT jboolean JNICALL Java_XXXAPI_nativeCheckSomeAccess
(JNIEnv *jnv, jobject jobj, jstring fresource, jstring uname){
jboolean accessible;
int ierror;
// convert jstring to char pointers
const char resname = (jnv)->GetStringUTFChars(jnv, fresource, 0);
const char u = (jnv)->GetStringUTFChars(jnv, uname, 0);
// pass parameters and check access
int canAccess = checkSomeAccess(resname, user, &ierror);
if(!ierror && canAccess == 1)
accessible = true;
else
accessible = false;
// release variables from JNI environment
(*jnv)->ReleaseStringUTFChars(jnv, fresource, resname);
(*jnv)->ReleaseStringUTFChars(jnv, uname, u);
return accessible;
the checkSomeAccess in "someCfile.h" actually looks like this:
int checkSomeAccess(char resname, char u, <enumeration> *ptr_to_enum_containing_integers);
</code>
When compiled the code... I am getting the following errors:
some_jni.c: In function `Java_XXXAPI_nativeCheckSomeAccess':
some_jni.c:65: warning: passing arg 1 of `checkSomeAccess' discards qualifiers from pointer target type
some_jni.c:65: warning: passing arg 2 of `checkSomeAccess' discards qualifiers from pointer target type
some_jni.c:65: warning: passing arg 3 of `checkSomeAccess' from incompatible pointer type
some_jni.c:67: `true' undeclared (first use in this function)
some_jni.c:69: `false' undeclared (first use in this function)
Please tell me, what is the problem here.
thank you,
Ran.Hi All,
How to convert an enum in C to Java-JNI ? I have the following enum defined in C.
typedef enum{
ERR_NOERROR=0,
ERR_INTERNAL,
ERR_NOOBJECT,
ERR_INVALIDOBJ,
}error_t;I am using this enum in my C function (in the header file) as:
int isSuccess(char* some_name, error_t *error);Now, while writing the JNI implementation for this, I have actually passed an integer which is giving compile time warning:
int result;
char *sn = (char*)(*env)->GetStringUTFChars(env, jstring_val, 0);
int errorCode;
result = isSuccess(sn, &errorCode);I would like to know, how to represent the enum type in JNI. It would be grateful If you provide an example code snippet.
thanks in advance,
Ran. -
Passing (byref) String from Java to C++ via JNI
I wish to pass a string to a C++ Dll as a parameter in a function. The problem is that I don't know howto receive back the data after it is filled in the C++ dll. I am trying to do what is called passing parameters by reference.
Java Code:
public class ABKeyBoard {
public native long leerBanda(int pista, String datos);
public static void main(String[] args) {
String datos=new String();
System.loadLibrary("ABKeyBoard");
new ABKeyBoard().leerBanda(1,datos);
System.out.println(datos); //the content of datos here is empty.
C++ Code:
Java_ABKeyBoard_leerBanda(JNIEnv *env, jobject obj,jint pista, jstring datos)
char buffer[2024];
memset(buffer, 0x00, sizeof(buffer));
strcpy(buffer, "xxxx");
datos = env->NewStringUTF(buffer);
return;
Thanks for your help.In java every parameter are always passed by value.
The datos parameter is a local copy of the string
reference you pass to the method.This is wrong. The String passed to the native method is the same String object you use in Java. Although everything is passed by value in Java, what is actually passed by value is the reference to the String. This means that you can modify the object you pass, but you are not allowed to change the reference to point to a totally different object. That is where the problem is coming in.
The trouble is that it is illegal to modify a String, even from native code. If you need to make changes in-place to the text, pass an array of chars (if your native code uses Unicode), an array of bytes (if it uses normal 8-bit characters) or a StringBuffer. You can legally modify any of these data structures with the new data. But the StringBuffer object is the only one whose length can be changed after it is created. Unfortunately it is also the hardest to use from JNI.
Generally I think you should always pass arrays of bytes/chars to native code instead of Strings when possible. They can be modified in place, and you can use String's methods to get a byte-array in the platform's proper encoding. Using the GetStringUTFChars method is problematic because UTF only maps directly onto ASCII in the case of characters which are in the set of 7-bit ASCII characters. Your code will do wrong things if your String happens to contain some other character, unless your native code expects UTF format strings.
The good news is that C(++) functions which return results in their arguments do not ordinarily change the length. So you should be able to allocate a byte[] or char[] ahead of time of the appropriate size (don't forget to add the trailing null, which is not a component of Java strings). I think byte[] or char[] is the best answer because you can easily map those onto C-style arrays with Get[Primitive]ArrayRegion; the return of that is suitable for passing directly to native code, as long as you have remembered the null-terminator. For instance you could do (*env)->GetByteArrayRegion(env, javaArray, 0, arrayLength, CArray) and then your CArray would be changed to point at the contents of the javaArray (note: it does not copy data into CArray, it changes CArray to point at the array contents, so do not allocate memory for CArray first). Then when you do ReleaseByteArrayRegion the results will be propagated back to Java. -
Creating a shared library for JNI in windows
I went through the JNi tutorial online and it worked just fine on a Linux computer. Now I'm trying to make do the same tutorial on windows. When I get to the step 4. Create a Shared Library, I'm stuck. I don't know how to create this shared library on windows. It gives an example using Visual C++ but I don't have that. Any tips or advice out there what I should do? Any help would be greatly appreciated.
//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 -
For my application, I want only one instance to be active at once. I use this Win32 method to do it:
JNIEXPORT void JNICALL Java_Server_multipleInstanceBlocker
(JNIEnv * env, jobject objThis, jstring instanceName)
char* mutexInstanceName = (char*)env->GetStringUTFChars(instanceName, 0);
HANDLE mutex = CreateMutex(NULL,true,mutexInstanceName);
if ( GetLastError() == ERROR_ALREADY_EXISTS )
String msg;
msg = "An instance of ";
msg += mutexInstanceName;
msg += " is running!\n\nCheck the task bar for ";
msg += "the icon!";
MessageBox(NULL, msg, "WARNING",MB_OK | MB_ICONWARNING);
exit( 0 );
It crashes when the application is run the second time. The MessageBox dissapears and an error message box appears saying that
Javaw has caused an error in MSVCRT.DLL.
Javaw will now close.
What does that mean?This is the crash report given by the jvm
For some strange reason, if i use java and not javaw, it never crashes...
# An unexpected error has been detected by HotSpot Virtual Machine:
# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x7800d77a, pid=-771569, tid=4294303003
# Java VM: Java HotSpot(TM) Client VM (1.5.0_04-b05 mixed mode)
# Problematic frame:
# C [MSVCRT.DLL+0xd77a]
--------------- T H R E A D ---------------
Current thread (0x006b9380): JavaThread "AWT-Shutdown" [_thread_in_native, id=-664293]
siginfo: ExceptionCode=0xc0000005, writing address 0x63d5216d
Registers:
EAX=0x00590078, EBX=0x0069000c, ECX=0x63692025, EDX=0x006c014c
ESP=0x0b3bf4c0, EBP=0x0b3bf4e0, ESI=0x0000003f, EDI=0x006c100c
EIP=0x7800d77a, EFLAGS=0x00010202
Top of Stack: (sp=0x0b3bf4c0)
0x0b3bf4c0: 00000038 00000040 00000000 819d6c3c
0x0b3bf4d0: 00000040 005909cc 63692025 00000004
0x0b3bf4e0: 0b3bf520 7800cfd8 0069000c 005f0a80
0x0b3bf4f0: 00000000 006a3540 0b3bf53c 0000001e
0x0b3bf500: 00000000 00000038 0b3bf53c 0b3bf2f0
0x0b3bf510: 0b3bfa48 7800f56a 780333a8 00000000
0x0b3bf520: 0b3bf560 6d637a75 00000001 00000040
0x0b3bf530: 006a3540 005f0a80 00000000 04034b50
Instructions: (pc=0x7800d77a)
0x7800d76a: 8b 4d fc 09 7c 88 44 8b 4d f8 85 c9 74 06 89 0a
0x7800d77a: 89 4c 11 fc 8b 75 f0 03 d1 8d 4e 01 89 0a 89 4c
Stack: [0x0b370000,0x0b3d0000), sp=0x0b3bf4c0, free space=317k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
C [MSVCRT.DLL+0xd77a]
C [MSVCRT.DLL+0xcfd8]
C [ZIP.DLL+0x7a75]
C [ZIP.DLL+0x78e2]
C [ZIP.DLL+0x7f3e]
V [JVM.DLL+0x4d5f3]
V [JVM.DLL+0xf3d29]
V [JVM.DLL+0xf3668]
V [JVM.DLL+0xf3152]
V [JVM.DLL+0xf305e]
V [JVM.DLL+0x5fdfd]
V [JVM.DLL+0x7d113]
j java.util.Hashtable.values()Ljava/util/Collection;+8
j sun.awt.AppContext.getAppContexts()Ljava/util/Set;+29
j sun.awt.AppContext.stopEventDispatchThreads()V+0
j sun.awt.AWTAutoShutdown.run()V+155
j java.lang.Thread.run()V+11
v ~StubRoutines::call_stub
V [JVM.DLL+0x82696]
V [JVM.DLL+0xd6fd9]
V [JVM.DLL+0x82567]
V [JVM.DLL+0x822c4]
V [JVM.DLL+0x9d216]
V [JVM.DLL+0x101489]
V [JVM.DLL+0x101457]
C [MSVCRT.DLL+0x248d]
C [KERNEL32.DLL+0x19391]
C [KERNEL32.DLL+0x16e3a]
Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
j java.util.Hashtable.values()Ljava/util/Collection;+8
j sun.awt.AppContext.getAppContexts()Ljava/util/Set;+29
j sun.awt.AppContext.stopEventDispatchThreads()V+0
j sun.awt.AWTAutoShutdown.run()V+155
j java.lang.Thread.run()V+11
v ~StubRoutines::call_stub
--------------- P R O C E S S ---------------
Java Threads: ( => current thread )
0x006c0a40 JavaThread "AWT-EventQueue-0" [_thread_blocked, id=-665813]
0x006bae80 JavaThread "AWT-Windows" daemon [_thread_in_native, id=-664681]
=>0x006b9380 JavaThread "AWT-Shutdown" [_thread_in_native, id=-664293]
0x006b83f0 JavaThread "Java2D Disposer" daemon [_thread_blocked, id=-663825]
0x006af800 JavaThread "Low Memory Detector" daemon [_thread_blocked, id=-720141]
0x006aec10 JavaThread "CompilerThread0" daemon [_thread_blocked, id=-719801]
0x006ada30 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=-718389]
0x006ace80 JavaThread "Finalizer" daemon [_thread_blocked, id=-694933]
0x006abb80 JavaThread "Reference Handler" daemon [_thread_blocked, id=-694529]
0x006a2d10 JavaThread "main" [_thread_in_native, id=-771845]
Other Threads:
0x006aae10 VMThread [id=-694205]
0x006b1f50 WatcherThread [id=-720529]
VM state:not at safepoint (normal execution)
VM Mutex/Monitor currently owned by a thread: None
Heap
def new generation total 576K, used 474K [0x02c50000, 0x02cf0000, 0x03130000)
eden space 512K, 80% used [0x02c50000, 0x02cb6898, 0x02cd0000)
from space 64K, 100% used [0x02ce0000, 0x02cf0000, 0x02cf0000)
to space 64K, 0% used [0x02cd0000, 0x02cd0000, 0x02ce0000)
tenured generation total 1408K, used 194K [0x03130000, 0x03290000, 0x06c50000)
the space 1408K, 13% used [0x03130000, 0x03160a80, 0x03160c00, 0x03290000)
compacting perm gen total 8192K, used 5047K [0x06c50000, 0x07450000, 0x0ac50000)
the space 8192K, 61% used [0x06c50000, 0x0713dd58, 0x0713de00, 0x07450000)
No shared spaces configured.
Dynamic libraries:
0x6d1c0000 - 0x6d210000 C:\WINDOWS\DESKTOP\V-KEY\PROGRAMMING\JAVA\CHATROOM\SERVER\WIN32.DLL
0x65480000 - 0x654d0000 C:\WINDOWS\DESKTOP\V-KEY\PROGRAMMING\JAVA\CHATROOM\SERVER\TASKBAR.DLL
0x63700000 - 0x63752000 C:\WINDOWS\DESKTOP\V-KEY\PROGRAMMING\JAVA\CHATROOM\SERVER\ICON.DLL
0x10000000 - 0x10024000 C:\WINDOWS\SYSTEM\HOOK98.DLL
0x6d240000 - 0x6d27d000 C:\PROGRAM FILES\JAVA\JRE1.5.0_04\BIN\FONTMANAGER.DLL
0x56660000 - 0x56740000 C:\WINDOWS\SYSTEM\D3DIM700.DLL
0xbaaa0000 - 0xbab03000 C:\WINDOWS\SYSTEM\DDRAW.DLL
0xbfe70000 - 0xbfe75000 C:\WINDOWS\SYSTEM\NTDLL.DLL
0x6d000000 - 0x6d167000 C:\PROGRAM FILES\JAVA\JRE1.5.0_04\BIN\AWT.DLL
0x76570000 - 0x76576000 C:\WINDOWS\SYSTEM\RSRC32.DLL
0x7f2d0000 - 0x7f30d000 C:\PROGRAM FILES\JAVA\JRE1.5.0_04\BIN\UNICOWS.DLL
0x7e480000 - 0x7e491000 C:\WINDOWS\SYSTEM\AVICAP32.DLL
0x77ee0000 - 0x77f04000 C:\WINDOWS\SYSTEM\MSVFW32.DLL
0xbfdc0000 - 0xbfdc5000 C:\WINDOWS\SYSTEM\WOW32.DLL
0x7d190000 - 0x7d196000 C:\WINDOWS\SYSTEM\DCIMAN32.DLL
0x7fe50000 - 0x7fe76000 C:\WINDOWS\SYSTEM\OLEDLG.DLL
0x7fb50000 - 0x7fb95000 C:\WINDOWS\SYSTEM\MSVCRT20.DLL
0xbfe50000 - 0xbfe56000 C:\WINDOWS\SYSTEM\VERSION.DLL
0x7fe00000 - 0x7fe33000 C:\WINDOWS\SYSTEM\COMDLG32.DLL
0x7fbd0000 - 0x7fdfe000 C:\WINDOWS\SYSTEM\SHELL32.DLL
0xbfb70000 - 0xbfbf8000 C:\WINDOWS\SYSTEM\COMCTL32.DLL
0x70a70000 - 0x70ad6000 C:\WINDOWS\SYSTEM\SHLWAPI.DLL
0x7f160000 - 0x7f16e000 C:\WINDOWS\SYSTEM\MPR.DLL
0x7ff20000 - 0x7ffe2000 C:\WINDOWS\SYSTEM\OLE32.DLL
0xbfe00000 - 0xbfe04000 C:\WINDOWS\SYSTEM\IMM32.DLL
0x7fe40000 - 0x7fe49000 C:\WINDOWS\SYSTEM\WINSPOOL.DRV
0x6d630000 - 0x6d63f000 C:\PROGRAM FILES\JAVA\JRE1.5.0_04\BIN\ZIP.DLL
0x6d300000 - 0x6d31d000 C:\PROGRAM FILES\JAVA\JRE1.5.0_04\BIN\JAVA.DLL
0x6d610000 - 0x6d61c000 C:\PROGRAM FILES\JAVA\JRE1.5.0_04\BIN\VERIFY.DLL
0x6d280000 - 0x6d288000 C:\PROGRAM FILES\JAVA\JRE1.5.0_04\BIN\HPI.DLL
0x6d640000 - 0x6d7c9000 C:\PROGRAM FILES\JAVA\JRE1.5.0_04\BIN\CLIENT\JVM.DLL
0xbfdd0000 - 0xbfde0000 C:\WINDOWS\SYSTEM\WINMM.DLL
0x00400000 - 0x0040c000 C:\PROGRAM FILES\JAVA\JRE1.5.0_04\BIN\JAVAW.EXE
0x78000000 - 0x78046000 C:\WINDOWS\SYSTEM\MSVCRT.DLL
0xbff40000 - 0xbff51000 C:\WINDOWS\SYSTEM\USER32.DLL
0xbff10000 - 0xbff3a000 C:\WINDOWS\SYSTEM\GDI32.DLL
0xbfe60000 - 0xbfe70000 C:\WINDOWS\SYSTEM\ADVAPI32.DLL
0xbff60000 - 0xbffe3000 C:\WINDOWS\SYSTEM\KERNEL32.DLL
VM Arguments:
java_command: C:\WINDOWS\Desktop\V-Key\programming\java\Chatroom\server\Server.jar
Environment Variables:
PATH=C:\WINDOWS;C:\WINDOWS\COMMAND;C:\Program Files\Java\jdk1.5.0_04\bin;C:\DJGPP\BIN
--------------- S Y S T E M ---------------
OS: Windows Me Build 73010104
CPU:total 1 family 15, cmov, cx8, fxsr, mmx, sse, sse2, ht
Memory: 4k page, physical 261552k(10068k free), swap 1835596k(1637520k free)
vm_info: Java HotSpot(TM) Client VM (1.5.0_04-b05) for windows-x86, built on Jun 3 2005 02:10:41 by "java_re" with MS VC++ 6.0 -
Trouble returning String from JNI method
I'm a JNI newbie who is going through the SUN online book on JNI and have put together the 2nd program example (right after "helloworld"), but it is not working right. It is supposed to prompt you for a string, then returns the string that you type in. Right now it compiles without error, but it returns only the first word that I type, not the whole sentence. What am I doing wrong?
Here's the code:
Prompt.java
package petes.JNI;
public class Prompt
private native String getLine(String prompt);
static
System.loadLibrary("petes_JNI_Prompt");
public static void main(String[] args)
Prompt p = new Prompt();
String input = p.getLine("Type a line: ");
System.out.println("User typed: " + input);
}petes_JNI_Prompt.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class petes_JNI_Prompt */
#ifndef _Included_petes_JNI_Prompt
#define _Included_petes_JNI_Prompt
#ifdef __cplusplus
extern "C" {
#endif
* Class: petes_JNI_Prompt
* Method: getLine
* Signature: (Ljava/lang/String;)Ljava/lang/String;
JNIEXPORT jstring JNICALL Java_petes_JNI_Prompt_getLine
(JNIEnv *, jobject, jstring);
#ifdef __cplusplus
#endif
#endifpetes_JNI_Prompt.c
#include <jni.h>
#include <stdio.h>
#include "petes_JNI_Prompt.h"
JNIEXPORT jstring JNICALL Java_petes_JNI_Prompt_getLine
(JNIEnv *env, jobject this, jstring prompt)
char buf[128];
const jbyte *str;
str = (*env)->GetStringUTFChars(env, prompt, NULL);
if (str == NULL)
return NULL; /* OutOfMemoryError already thrown */
printf("%s", str);
(*env)->ReleaseStringUTFChars(env, prompt, str);
// assume here that user will ty pe in 127 or less characters
scanf("%s", buf);
return (*env)->NewStringUTF(env, buf);
}Thanks in advance!
/PeteOK, I have something that works now by substituting fgets for scanf. I have two other questions:
1) Do I need to free the memory created in buf? Will it allocate memory every time the method is run? Or will it allocate only once on creation, and so is no big deal?
2) A minor question: When I run this program in eclipse, the prompt string is displayed in the console only after the input string is entered and displayed. It works fine when I run it from the command line however. I have a feeling that this is a problem with how Eclipse deals with native methods and perhaps nothing I can fix. Any thoughts?
Thanks
Pete
Addendum, the updated code:
#include <jni.h>
#include <stdio.h>
#include "petes_JNI_Prompt.h"
JNIEXPORT jstring JNICALL Java_petes_JNI_Prompt_getLine
(JNIEnv *env, jobject this, jstring prompt)
char buf[128];
const jbyte *str;
str = (*env)->GetStringUTFChars(env, prompt, NULL);
if (str == NULL)
return NULL; /* OutOfMemoryError already thrown */
printf("%s", str);
(*env)->ReleaseStringUTFChars(env, prompt, str);
//scanf("%s", buf);
fgets(buf, 128, stdin);
return (*env)->NewStringUTF(env, buf);
}Message was edited by:
petes1234 -
Core dump in 238th call to CallObjectMethod
Hi,
Please can anyone help me with this problem. I have searched net but couldnt find an answer. I have a C code. this function when called in a for loop for 238th time it fails at exactly myjstr = (jstring) env->CallObjectMethod(obj, mid,args,args1);
c code:
char* getComplexTag(JNIEnv *env, jclass cls, jobject obj, char complexTag[50][100] ,char complexValue[50][100])
jmethodID mid;
jobjectArray args;
jobjectArray args1;
jstring myjstr;
char errorMessage[10];
char returnTag[1024];
char infoMessage [1024];\
int arrayCount;
strcpy(errorMessage,"ERROR");
mid = env->GetMethodID(cls,"getKeyValue", "([Ljava/lang/String;[Ljava/lang/String;)Ljava/lang/String;");
if (mid == 0)
{return errorMessage;}
arrayCount = 0;
args = env->NewObjectArray(8, strClass, newStr);
while(strlen(complexTag[arrayCount]) > 0 )
jstring temp1=env->NewStringUTF(complexTag[arrayCount]);
env->SetObjectArrayElement(args,arrayCount,temp1);
env->ReleaseStringUTFChars(temp1,complexTag[arrayCount]);
//env->SetObjectArrayElement(args,arrayCount,env->NewStringUTF(complexTag[arrayCount]));
arrayCount = arrayCount + 1;
arrayCount = 0;
args1 = env->NewObjectArray(8, strClass, newStr);
while( strlen(complexValue[arrayCount]) > 0 )
jstring temp1=env->NewStringUTF(complexValue[arrayCount]);
env->SetObjectArrayElement(args1,arrayCount,temp1);
env->ReleaseStringUTFChars(temp1,complexValue[arrayCount]);
//env->SetObjectArrayElement(args1,arrayCount,env->NewStringUTF(complexValue[arrayCount]));
arrayCount = arrayCount + 1;
if (args == 0)
{return errorMessage; }
myjstr = (jstring) env->CallObjectMethod(obj, mid,args,args1);
if(myjstr != NULL)
const char *temp=env->GetStringUTFChars(myjstr, 0);
strcpy(returnTag,temp);
env->ReleaseStringUTFChars(myjstr, temp);
if(env != NULL && myjstr != NULL)
{ env->DeleteLocalRef(myjstr); }
if(env != NULL && args != NULL)
{ env->DeleteLocalRef(args); }
if(env != NULL && args1 != NULL)
{ env->DeleteLocalRef(args1); }
mid = NULL;
return returnTag;
}You can start by...
1. Verify that every JNI call to check is checked for errors.
2. Every call that does a java type call must be checked for exceptions after it.
Note that if an exception occurs and you do not catch it then continuing with java calls will likely lead to corruption. -
Problems using JNI and JSP in WebLogic 6.0
Hello everybody. My problem is that I've got a Java class that is called from a JSP. That class connects to a C function and it returns a String. A want this string to be shown by the JSP. The code is:
JSP
<html>
<head>
<title>prueba JNI</title>
</head>
<body>
<%@ page import="ejemplosJNI.*, conversiones.*;"%>
<%
Texto texto = new Texto();
out.println(texto.realizado());
%>
</body>
</html>
Java class
package ejemplosJNI;
public class Texto
private native String getLine(String prompt);
String input = null;
public static void main(String args[])
Texto t = new Texto();
static
System.loadLibrary("MyImpOfPrompt");
public String realizado()
input = this.getLine("Mando una l�nea desde Java");
return input;
C function
#include <stdio.h>
#include <jni.h>
#include "Texto.h"
JNIEXPORT jstring JNICALL
Java_Texto_getLine(JNIEnv *env, jobject obj, jstring prompt)
char buf[128];
const char str = (env)->GetStringUTFChars(env, prompt, 0);
(*env)->ReleaseStringUTFChars(env, prompt, str);
return (*env)->NewStringUTF(env, str);
I compile de C function and put the .dll library in the 'bin' folder in webLogic.
When I call the JSP, I get the next exception:
Servlet failed with Exception
java.lang.UnsatisfiedLinkError: getLine
at ejemplosJNI.Texto.getLine(Native Method)
at ejemplosJNI.Texto.realizado(Texto.java:19)
at jsp_servlet._jsp._pruebasjni._prueba1._jspService(_prueba1.java:93)
at weblogic.servlet.jsp.JspBase.service(JspBase.java:27)
at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubIm
pl.java:213)
at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubIm
pl.java:246)
at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppSe
rvletContext.java:1265)
at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestIm
pl.java:1622)
at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:137)
at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
Is there any place where I have to put the .dll?
Is there any place where I have to put the generated .lib?
Where do I have to put the Texto.h file generated with javah?
Can anybody help me to solve this problem?
Thanks in advance.Hi, jschell! Maybe you can see my problem if I give you the code. My Java class and the C funtions are:
Java class
package ejemplos.cadena;
public class Texto
private native String getLine(String prompt) throws Exception;
String cadenaFinal = null;
public static void main(String args[])
Texto t = new Texto();
static
System.loadLibrary("LibreriaCadena");
public String realizado(String cadena)
try
cadenaFinal = getLine(cadena);
catch(Exception e)
System.out.println(e.toString());
return cadenaFinal;
C code
#include <stdio.h>
#include <jni.h>
#include "ejemplos_cadena_Texto.h"
JNIEXPORT jstring JNICALL
Java_ejemplos_cadena_Texto_getLine(JNIEnv *env, jobject obj, jstring prompt)
int cero =0;
int division = 10 / cero;
const char str = (env)->GetStringUTFChars(env, prompt, 0);
(*env)->ReleaseStringUTFChars(env, prompt, str);
return (*env)->NewStringUTF(env, str);
I have done something like "int division = 10 / cero;" in order to get an exception in my C code. When I run my Java class I get an error message and the application breaks. I would like to know how to catch the C exception in order to pass it to my Java class that can manage it into the try-catch clause. I have read I have to use something like "FindClass" or "ThrowNew", but my problem is that I have no idea about C programming.
Can you help me?
Thanks for your time. -
Anyone can prove JNI is safe? My application crashes after many calls.
I heard that JNI is not safe. In fact I made an application base on many JNI calls.
C level is API supplied by IBM. And I was told the C API is tested and safe.
Java application and JNI calls is writen by myself. It crashed after about 3000 times call. I tried other JDK and other OS. On some platform, the thread hold there after many calls. No error, no crash. But others crashed even early.
Here's my JNI call's code:
JNIEXPORT void JNICALL Java_com_ibm_mm_sdk_cim_internal_PServiceFACImp_cEvaluate
(JNIEnv *env, jclass jobj, jlong jhandle, jstring jmanualedListFilename, jstring jclassedListFileName, jstring jresultFilename){
char *manualedListFilename = jstringToWindows(env, jmanualedListFilename);
char *classedListFileName = jstringToWindows(env, jclassedListFileName);
char *resultFilename = jstringToWindows(env, jresultFilename);
int rc; // API return code
void* handle; // FAC Handle
// convert C pointer from java long type
handle = (void*)jhandle;
rc = KmFAC_Evaluate(
handle, // FAC Handle
(char*)manualedListFilename, // File name of list of files
(char*)classedListFileName, // File name of list of files
(char*)resultFilename // Result file
if (manualedListFilename)
free(manualedListFilename);
if (classedListFileName)
free(classedListFileName);
if (resultFilename)
free(resultFilename);
if (rc != KM_RC_OK) {
//Throw exception
jclass exceptClass; // JNI exception class
char errorMsg[256]; // Used to build error msg for exceptions
jmethodID methodid; // Exception constructor method id
sprintf(errorMsg, "KmFAC_Evaluate() [CKM=%d]", (int)rc);
exceptClass = env->FindClass("com/ibm/mm/sdk/cim/DKServiceExceptionCIM");
methodid = env->GetMethodID(exceptClass,"<init>","(Ljava/lang/String;II)V");
jstring str = env->NewStringUTF(errorMsg);
jthrowable excobj = (jthrowable)env->NewObject(exceptClass,methodid,str,100, (int)rc);
env->Throw(excobj);
return;I agree with fury88. Try the code below it works fine!
// **************** Java portion ************************
public class Test {
// Load the dll that exports functions callable from java
static {System.loadLibrary("TestImp");}
// Imported function declarations
public native void print(String msg);
public void Test() {
public static void main(String [] args) {
Test t = new Test();
// Printf example
t.print("->Testing JNI - Hello from c++\n");
// **************** Windows portion - TestImp.dll **********************
// Exported function
JNIEXPORT void JNICALL Java_Test_print(JNIEnv *env, jobject obj, jstring msg)
const char *str = env->GetStringUTFChars(msg, 0);
printf("%s\n", str);
env->ReleaseStringUTFChars(msg, str);
// Entry point
BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
switch(ul_reason_for_call)
case DLL_PROCESS_ATTACH:
return TRUE;
case DLL_PROCESS_DETACH:
return TRUE;
return TRUE;
} -
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
Maybe you are looking for
-
How to Set Classpath in servlet
Hi Friends, I want to call class with using reflection in my "servlet" , since class which I am calling is stand alone java program and it is not in web application. It is stored else where on server in Offline process. So how can I call the method o
-
6th Generation Classic - External Speakers
Previously, I had a 5th Generation Classic iPod (60GB) that when connected to external speakers, had an option (within the Speakers menu) to show large album cover artwork during song play. And when a song was playing, the album cover, on a black ba
-
At the time of Rebate TDS was not calculate.
Hello Experts, At time of Rebate (SD) to the customer that time client wants calculate TDS (Sec.194H) i have assign TDS Tax code in Customer master (FD02). After that made the entry of Rebate. when i see the display entry no was TDS calculate. waitin
-
Everytime I want to save a file, the save file dialog box loses focus to the main firefox window. I habitually use the keyboard shortcut "ALT+S" to save the file to my specified location. Since the save file dialog box now always loses focus, I can't
-
HI, I just bought a macbook air. While setting it up, I should have done something wrong. As a consequence, I have a macbook air with an unknown password. How can I reset it even if it erase all datas ? Thanks for your support. JEFF