用c ++编写的库可产生连续的数据流,并且必须将其移植到不同的平台上。现在将lib集成到android应用程序中,我试图在NDK和SDK之间创建共享内存。
下面是工作片段,
本地代码:
#include <jni.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <linux/ashmem.h>
#include <android/log.h>
#include <string>
char *buffer;
constexpr size_t BufferSize=100;
extern "C" JNIEXPORT jbyteArray JNICALL
Java_test_com_myapplication_MainActivity_getSharedBufferJNI(
JNIEnv* env,
jobject /* this */) {
int fd = open("/dev/ashmem", O_RDWR);
ioctl(fd, ASHMEM_SET_NAME, "shared_memory");
ioctl(fd, ASHMEM_SET_SIZE, BufferSize);
buffer = (char*) mmap(NULL, BufferSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
char *c = "Hello World 123 speaking";
std::strncpy(buffer,c,BufferSize);
return static_cast<jbyteArray>(env->NewDirectByteBuffer(buffer, BufferSize));
}
extern "C" JNIEXPORT void JNICALL
Java_test_com_myapplication_MainActivity_TestBufferCopy(
JNIEnv* env,
jobject /* this */) {
for(size_t i=0;i<BufferSize;i = i+2) {
__android_log_print(ANDROID_LOG_INFO, "native_log", "Count %d value:%d", i,buffer[i]);
}
}
SDK代码:
//MainActivity.java
public class MainActivity extends AppCompatActivity {
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
final int BufferSize = 100;
@RequiresApi(api = Build.VERSION_CODES.Q)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ByteBuffer byteBuffer = getSharedBufferJNI();
byte[] b = byteBuffer.array();
String s = new String(b,StandardCharsets.UTF_8 );
Log.i("sdk_log",s);
for(int i =0; i<BufferSize;i++) {
Log.i("sdk_log",i+" "+byteBuffer.get(i));
byteBuffer.put(i, (byte) (i+10));
}
TestBufferCopy();
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
public native ByteBuffer getSharedBufferJNI();
public native int TestBufferCopy();
}
问题:
c
和java
之间映射存储器的另一种方式>用c ++编写的库可产生连续的数据流,并且必须将其移植到不同的平台上。现在将lib集成到android应用程序中,我试图在...
让我总结一下我的发现,