Topic: jni小错误

  Print this page

1.jni小错误 Copy to clipboard
Posted by: manhunt
Posted on: 2006-04-23 11:07

照着"Java进阶-JNI使用技巧点滴(二)"中的例子编了个很小的程序,就是在java中定义一个字符串利用c显示出来。

其中一个c.cpp 用到自定义函数convertUniToANSI,用cl命令编译成dll文件时出现以下错误:

c.cpp ( 8 ) : error c2065: 'convertUniToANSI' : undeclared identifier
c.cpp ( 20 ) : error c2373: 'convertUniToANSI': redefinition; defferent type modifiers
=====================================
以下为代码:

c语言主程序c.cpp

#include <stdio.h>
#include "connection.h"
#include "windows.h"

JNIEXPORT void JNICALL Java_connection_HelloWorld (JNIEnv*env, jclass jobject,jstring text)
{
char* sp;
convertUniToANSI(env,text,sp);
printf("sp= %s\n",sp);
}
JNIEXPORT jstring JNICALL Java_connection_cToJava (JNIEnv *env,jclass obj)
{
jstring jstr;
char str[]="fuck this world!\n";
jstr=env->NewStringUTF(str);
return jstr;
}

void convertUniToANSI(JNIEnv *env,jstring oldStr,char* newStr)
{
int desc_len=256*2;
int len;
if(oldStr==NULL||newStr==NULL)
return ;
wchar_t *w_buffer = new wchar_t[256];
wcscpy(w_buffer,env->GetStringChars(oldStr,0));
env->ReleaseStringChars(oldStr,w_buffer);
len = WideCharToMultiByte(CP_ACP,0,w_buffer,1024,newStr,desc_len,NULL,NULL);
if(len>0 && len<desc_len)
{
newStr[len]='\0';
}
delete[] w_buffer;
}
=====================================
连接程序:connection.java

public class connection
{
static
{
System.loadLibrary( "c" );
}
public native static void HelloWorld(String text);
//public native static String cToJava();
}
====================================
测试程序:test.java

public class test
{
public static void main(String[] args)
{
connection b=new connection();
String text="fthe world!";
b.HelloWorld(text);
//System.out.println(b.cToJava());
}
}

test.rar (1.31k)

2.Re:jni小错误 [Re: manhunt] Copy to clipboard
Posted by: damondeng
Posted on: 2006-05-10 12:58

你把方法写在调用后面了...
在CPP里, 必须先写方法, 再写调用, 如果一定在要方法实现前调用, 需要在调用前声名一下.

写JNI和JVMPI, JVMTI等和C/C++相关的要注意培养C/C++的调试能力.

我没拿程序来编译(机器刚当了,没安装), 从程序看应该是这个问题

3.Re:jni小错误 [Re: manhunt] Copy to clipboard
Posted by: ranchgirl
Posted on: 2006-05-17 14:07

Here is an excellent JNI course notes with exercises and complete solutions.
Take a look!

Programmming in C/C++ with the Java Native Interface


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923