我一直在尝试使用 Xamarin Studio 将一个简单的 hello world NDK 项目导入一个 monodroid 项目。
项目的 NDK 部分可以正常编译和构建,我可以调用本机方法,但是当我尝试使用JNIEnv
SIGSEGV 访问应用程序崩溃时,请参阅下面的控制台输出和相关代码片段。
Very basic console logging
Starting method
Accessing env
Stacktrace:
at <unknown> <0xffffffff>
at (wrapper managed-to-native) BasicNDK.Activity1.LogNdk (string) <IL 0x00032, 0xffffffff>
at BasicNDK.Activity1.<OnCreate>b__0 (object,System.EventArgs) [0x00023] in c:\Users\cbramley\Documents\Visual Studio 2012\Projects\AndroidApplication1\BasicNDK\MainActivity.cs:56
at Android.Views.View/IOnClickListenerImplementor.OnClick (Android.Views.View) [0x0000c] in /Users/builder/data/lanes/monodroid-mlion-master/bf2b736d/source/monodroid/src/Mono.Android/platforms/android-10/src/generated/Android.Views.View.cs:643
at Android.Views.View/IOnClickListenerInvoker.n_OnClick_Landroid_view_View_ (intptr,intptr,intptr) [0x00011] in /Users/builder/data/lanes/monodroid-mlion-master/bf2b736d/source/monodroid/src/Mono.Android/platforms/android-10/src/generated/Android.Views.View.cs:614
at (wrapper dynamic-method) object.6ea2e501-d56c-455b-9c13-849da747461e (intptr,intptr,intptr) <IL 0x00017, 0x00043>
at (wrapper native-to-managed) object.6ea2e501-d56c-455b-9c13-849da747461e (intptr,intptr,intptr) <IL 0x00023, 0xffffffff>
=================================================================
Got a SIGSEGV while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries
used by your application.
=================================================================
monodroid 活动代码:
// snipped rest of activity
[DllImport ("ndksample")]
static extern void LogNdk ( string w );
[DllImport ("ndksample")]
static extern void LogNdkDefaultMessage ();
protected override void OnCreate ( Bundle bundle )
{
base.OnCreate ( bundle );
SetContentView ( Resource.Layout.Main );
Button button = FindViewById<Button> ( Resource.Id.myButton );
button.Click += delegate
{
// launch our NDK code
try
{
LogNdkDefaultMessage();
LogNdk("Message to log");
}
catch (Exception e)
{
Log.Warn("MainShort",e.ToString());
}
};
}
最后是 NDK 实现:
#include <jni.h>
#include <string.h>
#include <android/log.h>
#define DEBUG_TAG "NDK_AndroidNDK1SampleActivity"
void LogNdk(JNIEnv * env, jobject this, jstring logThis)
{
__android_log_print(ANDROID_LOG_DEBUG, DEBUG_TAG, "Starting method");
jboolean isCopy;
__android_log_print(ANDROID_LOG_DEBUG, DEBUG_TAG, "Accessing env");
const char * szLogThis = (*env)->GetStringUTFChars(env, logThis, &isCopy);
__android_log_print(ANDROID_LOG_DEBUG, DEBUG_TAG, "NDK:LC: [%s]", szLogThis);
(*env)->ReleaseStringUTFChars(env, logThis, szLogThis);
__android_log_print(ANDROID_LOG_DEBUG, DEBUG_TAG, "Finished");
}
void LogNdkDefaultMessage(JNIEnv * env, jobject this)
{
__android_log_print(ANDROID_LOG_DEBUG, DEBUG_TAG, "Very basic console logging");
}
我已经将问题追踪到这条线路上的崩溃,const char * szLogThis = (*env)->GetStringUTFChars(env, logThis, &isCopy);
但我不明白是什么原因造成的,有人可以帮我解释一下吗?或者更好的是告诉我如何解决它:)