Reputation: 2136
I have a Java-based Android app that uses two native submodules. I have them sharing a pointer by retrieving it from process A as a long
and passing it to process B. I seem to encounter problems related to this memory region that are sporadic and depend upon the current build and not upon the changes I just made.
Do I need to use ashmem
to accomplish this properly, or is my methodology (in principal) sound?
Upvotes: 0
Views: 1768
Reputation: 4917
Here is what I would suggest:
1) Allocate shared memory through ashm:
int fd = ashmem_create_region(name, size);
ashmem_pin_region(fd, 0, 0);
uint8_t *shm = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
2) the fd can be shared with another native process using binder. For more info on binder please read this stack overflow answer.
3) In the other native code you can do:
uint8_t *shm = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fdclient, 0);
where fdclient is acquired in step 2) above.
Upvotes: 0
Reputation: 4917
It's impossible to share pointers between native apps since each (native) app has it's own memory space & mapping. Android does provide a mechanism to solve this problem, which is called Anonymous Shared Memory. This is actually based on linux's implementation for the same purpose. Checkout this document from android for more info on sharing memory in android.
Here are the scheme I used:
1)
fd = ashmem_create_region("my_shm_region", size);
if(fd < 0)
return -1;
unsigned char* dataptr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if(data == MAP_FAILED)
goto out;
2)You can then pass fd to other native app and call:
unsigned char* dataptr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
Upvotes: 0
Reputation: 533660
There is no guarantee that memory in one process which be a) accessible to another, b) in the same virtual location, c) thread safe.
What I do is memory map the same file into multiple processes and use the Unsafe class to perform thread safe operations on this memory.
This work on Intel and should work on the latest ARM processors, however older versions of ARM processors which I believe are still in use have weaker memory consistency guarantees, and may be unreliable for shared memory.
Upvotes: 1