Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C动态链接库 #45

Open
nonocast opened this issue Apr 18, 2020 · 0 comments
Open

C动态链接库 #45

nonocast opened this issue Apr 18, 2020 · 0 comments

Comments

@nonocast
Copy link
Owner

nonocast commented Apr 18, 2020

创建so

read.h

#ifndef READ_H
#define READ_H

int read();

#endif

read.c

#include "read.h"

int read() { return 123; }

Makefile

CC = gcc

build: read.o
	$(CC) -shared -o libReader330.so read.o

read.o: read.c
	$(CC) -c -o read.o read.c

.PHONY: build
$ make
gcc -c -o read.o read.c
gcc -shared -o libReader330.so read.o

然后就得到了so, 将此lib link到path中,

$ ln -s /.../.../libReader330.so /usr/local/lib

验证so

另起一个目录,

app.c

#include <stdio.h>

int read();

int main(void) {
  int ret = read();
  printf("ret: %d\n", ret);
  return 0;
}

Makefile

CC = gcc

build: 
	$(CC) -o app -lReader330 app.c

.PHONY: build

非常方便易懂:

$ make 
gcc -o app -lReader330 app.c
$ ./app
ret: 123

仔细考虑内存分配问题

read.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

unsigned char *SHGBIT_330_read(unsigned char **result) {
  char *message = "hello world, 330";
  int len = strlen(message);
  *result = (unsigned char *)malloc(len + 1);
  strcpy((char *)*result, message);
  *result[len] = 0x00;
  return *result;
}

app.c

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

unsigned char *SHGBIT_330_read(unsigned char **result);

int main(void) {
  unsigned char *result;
  printf("%s\n", SHGBIT_330_read(&result));
  free(result);
  return 0;
}

so负责分配(malloc)内存,调用方负责释放(free)内存。

@nonocast nonocast changed the title Java调用动态库(shared library) C动态链接库 Apr 18, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant