JNA를 사용하여 java에서 c 함수를 호출합니다. 이 기능은 사용자가 제공하는 메모리에 문자열 목록을 작성하고 서명을 읽 나는 다음과 같은 문제로 실행Java에서 C로 문자열 쓰기 가능 어레이 전달 (JNA 사용)
??llo world!
H
?
Hello world! Hallo Welt! Ciao a tutti!
0x48 0x65 0x6c 0x6c 0x6f 0x20 0x77 0x6f 0x72 0x6c 0x64 0x21 0x0 0x48 0x61 0x6c 0x6c 0x6f 0x20 0x57 0x65 0x6c 0x74 0x21 0x0 0x43 0x69 0x61 0x6f 0x20 0x61 0x20 0x74 0x75 0x74 0x74 0x69 0x21 0x0 ...
public interface TestCaseDLL extends Library
{
int c_getStrings(byte[] buf, int bufSize, Memory strings, IntByReference stringCount);
}
public class TestCase
{
public static void main(String[] args)
{
byte[] buf = new byte[100];
Memory strings = new Memory(Memory.SIZE * 10);
IntByReference stringCount = new IntByReference(10);
// c_getStrings() will write the strings continuously to 'buf' and
// additionally return a list of starting addresses through the
// 'strings' parameter (that is 'strings' point into 'buf').
// 'stringCount' holds the initial array size of 'strings' and will
// return the count of returned strings.
TestCaseDLL.INSTANCE.c_getStrings(buf, buf.length, strings, stringCount);
System.out.println(strings.getPointer(0).getString(0));
System.out.printf("%c\n", buf[0]); // how can this line change 'strings'?
System.out.println(strings.getPointer(0).getString(0));
for (byte b: buf) {
System.out.print((char) b);
}
System.out.println("");
for (byte b: buf) {
System.out.printf("%#x ", b);
}
System.out.println("");
}
}
출력 : Java 버전과
void c_getStrings(char *buf, size_t bufSize, char *strings[], size_t *stringsCount)
:
- 반환 된 st 반지가 부러졌습니다. "Hello World!"가 반환됩니다. "대신 세상에!"
- 인쇄
buf[0]
은 반환 된 문자열을 변경합니다. 나는 단지 그 가치를 읽으므로 여기에서 어떤 일이 일어나고 있는지 단서를 봤습니다.
내 형식 매핑이 손상되었거나 기본 사항이 누락 되었습니까?
업데이트
내가 지금 사용 사용
void c_getStrings(Memory buf, int bufSize, String[] strings, IntByReference stringCount);
나는 그것을 다시 할 경우에, 나는 두 가지 기능으로 분할 할 technomage에 의해 제안 :
void c_fill(char *buf, size_t bufSize);
void c_parseToStringArray(const char *buf, const char *strings[], size_t stringsSize);
정말 대단한 API입니다. – technomage
@technomage 문자열 목록을 반환하는 데 사용하는 C API는 무엇입니까? –
현재'c_getString'은 메모리를 할당하지 않습니다 (좋은 생각입니다).버퍼'buf '만 반환해도 충분하지만 문자열 배열'strings'을 사용하면 함수를 간단하게 사용할 수 있습니다. 동의하지 않니? –