我想在android studio中用JNI创建扑克应用,我想保存一个c++类(TexasHoldem)的实例,并在我写的texasJNI.java中只调用它的方法。
public class jniTexasHoldem {
private long texasHoldm;
jniTexasHoldem() {
ConstructNativeTexas();
}
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
private native void ConstructNativeTexas();
public native String getCardXML();
public native String stringFromJNI();
}
在mainActivity中:
ublic class MainActivity extends AppCompatActivity {
private jniTexasHoldem m_TexasHoldem = new jniTexasHoldem();
...
String cardXml = m_TexasHoldem.getCardXML();
}
和native-lib中,
extern "C"
JNIEXPORT jstring JNICALL
Java_android_myapplication_jniTexasHoldem_stringFromJNI(
JNIEnv* env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
extern "C"
JNIEXPORT jlong JNICALL
Java_android_myapplication_jniTexasHoldem_ConstructNativeTexas(JNIEnv *env, jobject thiz) {
TexasHoldm* texasHoldmObj = new TexasHoldm();
return (jlong)texasHoldmObj;
}
extern "C"
JNIEXPORT jstring JNICALL
Java_android_myapplication_jniTexasHoldem_getCardXML(JNIEnv *env, jobject thiz) {
jclass c = env->GetObjectClass(thiz);
// J is the type signature for long:
jfieldID fid_handle = env->GetFieldID(c, "texasHoldm", "J");
TexasHoldm * nativeObject = (TexasHoldm *) env->GetLongField(thiz, fid_handle);
return (env)->NewStringUTF(nativeObject->getCard().c_str());
}
我希望得到自动生成的{card}.png字符串。getCard
方法,但由于 undefined reference to 'TexasHoldm::getCard()'
externalNativeBuild {
cmake {
path "src/main/cpp/CMakeLists.txt"
version "3.10.2"
}
}
ndkVersion "21.1.6352462"
我在CmakeList中写道:"我想用JNI在android studio中创建一个扑克应用
target_link_libraries( # Specifies the target library.
native-lib
TexasHoldm.h
TexasHoldm.cpp
PokerTable.h
PokerTable.cpp
Player.h
Player.cpp
Hand.h
Hand.cpp
Card.h
Card.cpp
# Links the target library to the log library
# included in the NDK.
${log-lib} )
所有文件之间都有依赖关系,所以我清理了CMakeLists文件,因为它是一开始就有的(基本的自动生成文件,只有native-lib),我添加了以下内容 ndkVersion "21.1.6352462"
行,并将所有外部.cpp文件添加到了 add_library
部分在CMakeLists文件中。
add_library( # Sets the name of the library.
native-lib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
native-lib.cpp **extra .cpp files here**)
所以它把所有的内容都编译在一个外部lib中。