java调用c的方法,在生成dll库的时候,在java里不能调用??

东北的碳 2015-09-05 02:09:48
通过下面的代码生成的.dll文件java不能调用,请赐教
以下c代码如下:
#include "codec.h"

#include <sys/types.h>
#include <string.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>

//获得字符长度
jint getStrLen(JNIEnv* env, jstring str)
{
jint len = (*env)->GetStringLength(env,str);
return len;
}

//java字符串转C字符串
char* js2c(JNIEnv* env, jstring jstr) {
char* pstr = NULL;

jclass jstrObj = (*env)->FindClass(env, "java/lang/String");
jstring encode = (*env)->NewStringUTF(env, "utf-8");
jmethodID methodId = (*env)->GetMethodID(env, jstrObj, "getBytes","(Ljava/lang/String;)[B");
jbyteArray byteArray = (jbyteArray)(*env)->CallObjectMethod(env, jstr,methodId, encode);
jsize strLen = (*env)->GetArrayLength(env, byteArray);
jbyte *jBuf = (*env)->GetByteArrayElements(env, byteArray, JNI_FALSE);

if (jBuf > 0) {
pstr = (char*) malloc(strLen + 1);
if (!pstr) {
return NULL;
}

memcpy(pstr, jBuf, strLen);
pstr[strLen] = 0;
}

(*env)->ReleaseByteArrayElements(env, byteArray, jBuf, 0);

return pstr;
}

//C字符串转java字符串
jstring c2js(JNIEnv* env, const char* pstr) {
int strLen = strlen(pstr);

jclass jstrObj = (*env)->FindClass(env, "java/lang/String");
jmethodID methodId = (*env)->GetMethodID(env, jstrObj, "<init>","([BLjava/lang/String;)V");
jbyteArray byteArray = (*env)->NewByteArray(env, strLen);
jstring encode = (*env)->NewStringUTF(env, "utf-8");

(*env)->SetByteArrayRegion(env, byteArray, 0, strLen, (jbyte*) pstr);

return (jstring)(*env)->NewObject(env, jstrObj, methodId, byteArray, encode);
}

java 生成的.h文件代码如下:
#ifndef _CODEC_H_
#define _CODEC_H_

#ifdef __cplusplus
extern "C" {
#endif

#include <jni.h>

//获取字符串长度
jint getStrLen(JNIEnv* env, jstring str)

//java字符串转C字符串
char* js2c(JNIEnv* env, jstring jstr);

//C字符串转java字符串
jstring c2js(JNIEnv* env, const char* pstr);

#ifdef __cplusplus
}
#endif
#endif
...全文
122 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_221 2015-09-06
  • 打赏
  • 举报
回复

81,122

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧