2013-07-16 3 views
0

전역 문자열을 만들려면 경로명이 필요한 프로그램을 작성하고 있습니다. 현재이 경로명은 하드 코딩되어 있지만이를 대체하기 위해 전역 변수를 사용하고 싶습니다. 내가 가지고있는 문제는 내 전역 변수가 정의되지 않았다는 것입니다. 나는 또한 JNI를 사용하고 내가 점점 오전 오류는 다음과 같습니다어떻게 변수를 다른 클래스의 값으로 할당 할 수 있습니까?

#include <jni.h> 
#include "file1.h" 
#include <iostream> 
#include <fstream> 
#include <string.h> 

using namespace std; 
const char* myPath; 

JNIEXPORT jint JNICALL Java_foo_foo(JNIEnv *env, jobject thisobj, jbyteArray passedPath){ 

/*Some conversion, don't think it is relevant, but it might be*/ 

    jboolean isCopy; 
    jbyte* path = env->GetByteArrayElements(passedPath,&isCopy); 
    int length1 = strlen((const char*)path); 
    char* convertedVar = (char*)malloc(length1+1); 
    memcpy(convertedVar,path,length1); 
    convertedVar[length1] = '\0'; 
    convertedVar = (char*)path; 

/*End Conversion*/ 

    globalVariable = convertedVar; 

    ... //Some code to use the variable and releases 

} 

file2.h

file1.cpp (이 : 여기

# 
# A fatal error has been detected by the Java Runtime Environment: 
# 
# SIGSEGV (0xb) at pc=0x00007f65f981ddd0, pid=11660, tid=140075985102592 
# 
# JRE version: 7.0_21-b02 
# Java VM: OpenJDK 64-Bit Server VM (23.7-b01 mixed mode linux-amd64 compressed oops) 
# Problematic frame: 
# C [libstdc++.so.6+0x9ddd0] std::string::size() const+0x0 
# 
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again 
# 
# An error report file with more information is saved as: 
# /home/cbil/Desktop/SIGH_Project/July_9/src/hs_err_pid11660.log 
# 
# If you would like to submit a bug report, please include 
# instructions on how to reproduce the bug and visit: 
# https://bugs.launchpad.net/ubuntu/+source/openjdk-7/ 
# The crash happened outside the Java Virtual Machine in native code. 
# See problematic frame for where to report the bug. 
# 

및 것은 단순화를 위해 다시 포맷 관련 코드입니다 전역 변수를 선언하는 곳입니다.)

#include <vector> 
#include <fstream> 
#include <string.h> 

extern const char* globalVariable; 
extern int someNum; 
extern int someLength; 

class file2{ 
    public: 
     static std::vector<std::string> getSomeString(int &someNum, int &someLength); 

    private: 
     static const std::vector<std::string> anotherVar; 

     ...//some other variables and methods 

} 

마지막으로 getSomeString을 호출하는 코드

file3.cpp는

#include "file2.h" 
#include <string.h> 
#include <vector> 
#include <fstream> 

using namespace std; 

int someNum = 0; 
int someLength = 0; 
const char* globalVariable; 
vector<string> file2::getSomeString(int &someNum, iint &someLength){ 

    vector<string> data; 

    ifstream infile(globalVariable); //I think the problem is here 

    string line; 

    ...// some code that goes through the data file specified by the path name  

    someNum = data.size(); 
    someLength = data[0].size(); 


return data; 
} 

const vector<string> file2::anotherVar = getSomeString(someNum,someLength); //variable that uses the getSomeString method 

} 

내가 JNI를 사용하고, 여기서 다시 말할 것이다. 내가 만든 lib.so 파일에 정의되지 않은 변수가 있다고 말하는 오류가 발생했습니다. 이것이 유용한 정보인지는 잘 모릅니다. 도움이 될 것입니다. 긴 게시물에 대해 유감스럽게 생각합니다. 나는 길을 잃었습니다.

+0

변환 된 Var에 경로를 할당 한 후 malloc 된 메모리는 어떻게됩니까? –

+0

@NeilKirk 특별히 아무 것도하지 않습니다. malloc을 사용하여 끝에 '\ 0'을 추가 할 공간이 충분하여 cstring으로 인식 될 수 있도록했습니다. –

+0

저는 JNI에 익숙하지 않지만,'passedPath'는 NUL로 끝나는 것으로 생각합니까? Java는 일반적으로 이러한 방식으로 작동하지 않습니다. 커서 검색은'env-> GetArrayLength (passedPath)'를 호출하여 배열 크기를 알아낼 것으로 예상된다. –

답변

1
char* convertedVar = (char*)malloc(length1+1); 
memcpy(convertedVar,path,length1); 
convertedVar[length1] = '\0'; 
convertedVar = (char*)path; 

나는이 마지막 줄이 없어야한다고 확신합니다. 이 malloc/memcpy 춤을 뚫고 나면이 할당되고 초기화 된 메모리 블록을 바닥에 즉시 놓고 convertedVar이 다른 것을 가리 키도록하십시오.

또한, 나는 함수가 반환 되 자마자 path 포인터가 유효하지 않게 될 것이라고 확신합니다.

+0

포인터를 반환하고 무효화하는 함수에 대해 언급했는데 왜이 포인터가'path' 포인터를 무효화합니까? –

+0

저는 JNI에 익숙하지 않습니다. 내 생각에,'passedPath'로 표현 된 메모리 블록은이 JNI 호출의 지속 기간 동안 고정되어있다. 함수가 반환되면 블록은 고정 해제되고 가비지 수집기의 변덕에 따라 달라지며 가비지 수집기는 언제든지 이동하거나 할당 해제 할 수 있습니다. –

0

extern const char* globalVariable;

이것은 변수를 선언하지만 정의하지는 않습니다. 당신은 또한 (안 헤더 파일에) 정확히 하나 개의 소스 파일에 정의를 제공해야합니다

const char* globalVariable; 

호기심, 당신은 someNumsomeLength으로 그냥 할 정도로 알고 있지만 globalVariable합니다.

+0

죄송합니다. 오타였습니다. 원래는 오타였습니다. 캐치 덕분에 Editted,하지만 문제는 여전히 지속됩니다. –

+0

문제가 여전히 지속되는 이유는 무엇입니까? 오류 메시지에 대해 언급했는데 그 메시지의 정확한 텍스트는 무엇입니까? –

+0

스레드 "main"의 예외 java.lang.UnsatisfiedLinkError : .../libfoo.so : .../libfoo.so : 정의되지 않은 기호 : globalVariable \t at java.lang.ClassLoader $ NativeLibrary.load (Native Method) java.lang.ClassLoader.loadLibrary1에서 \t (ClassLoader.java:1935) java.lang.ClassLoader.loadLibrary0에서 \t (ClassLoader.java:1860) java.lang.ClassLoader.loadLibrary에서 \t (ClassLoader.java:1850) \t at java.lang.Runtime.loadLibrary0 (Runtime.java:845) \t at java.lang.System.loadLibrary (System.java:1084) \t at tcr. (foo.java:9) –

관련 문제