How to create native C++ library on Android?

2019-03-19 10:20发布

I need to write a dynamic link library in C++ that is used by Java on Android. As I get, it should be .so library, but I don't know how to do that. I tried Cygwin, but it crashes:

$ gcc 1.cpp

/usr/lib/gcc/i686-pc-cygwin/4.3.4/../../../../i686-pc-cygwin/bin/ld: cannot find -luser32 collect2: ld returned 1 exit status

1.cpp:
int main(int, char**)
{
   return 0;
}

Can anyone help me with that?

P.S. I'm not good at *nix, so it should be better done under Windows

UPD: I've installed both Android NDK and Cygwin and added them to PATH environment variable

UPD2: Thanks for helping. The problem was with Cygwin itself. Reinstalling it and NDK solved the problem.

3条回答
做自己的国王
2楼-- · 2019-03-19 10:41

For your example, use g++ instead of gcc, its a C++ program.

Look at the hello-jni sample in the NDK. You need to build your shared library using the NDK and import it into a Java Android project. In the Java code, you need to declare the native functions with 'native' and add the library using static; see snippet below.

public native String  stringFromJNI();

static {
    System.loadLibrary("hello-jni");
}
查看更多
Rolldiameter
3楼-- · 2019-03-19 10:52

You'll probably need the Android NDK to compile and link native libraries on Android. Cygwin and windows should work (cygwin provides the required *nix tools).

To me it looks like you compiled the c++ source for a WINTEL environment, which is totally different from android phones. So if you load that library to the phone, it will certainly crash/not work at all.

Here is an article that might help. It covers the android-ndk/cygwin part and should provide some pointers to more information.

EDIT

sigh - handed part of the error message to google and was surprised that there are no results with the user32 lib ... then I realized, that the part -luser32 effectively removed all user32 related links from the result list ;)

This is the most promising link: http://www.cygwin.com/ml/cygwin/2003-01/msg00292.html

Basiscally - run cygwin setup and add the package that contains the user32 lib. Then it should work.

查看更多
ら.Afraid
4楼-- · 2019-03-19 11:06

Look at the samples that come with the NDK. You need to use JNI bindings to allow it to communciate with Java. Under those bindings you can do whatever you like but anything that needs to be accessible from Java needs to go through the JNI bindings. Anything that DOESN'T need to be accessible can be written just as you normally would.

And yes its perfectly doable under windows.

查看更多
登录 后发表回答