C 호출이 버퍼와 크기가 전달 될 것으로 예상하는 OCaml에서 네이티브 OSX 호출을 매핑하는 데 문제가 있습니다. CTypes 및 Foreign 사용에 대한 Real World OCaml의 예제를 통해 작업했지만이 경우는 다루지 않습니다. 아니면 적어도 내가 어떻게했는지는 분명하지 않습니다.
다음은 OCaml의 일부입니다.
open Core.Std
open Unix
open Ctypes
open Foreign
(* from /usr/include/libproc.h
int proc_pidpath(int pid, void * buffer, uint32_t buffersize);
*)
let proc_pidpath = foreign "proc_pidpath" (int @-> ptr void @-> int @-> returning int)
let () =
let pid = Pid.to_int (Unix.getpid ()) in
let buf = allocate string 255 in
let path = proc_pidpath(pid, buf, 255) in
printf "Pid: %i Path: %s\n" pid buf
전달할 버퍼를 어떻게 할당하고 proc_pidpath()
Option 유형 (String 또는 Nil) 또는 문자열 만 반환하도록이 호출을 래핑하는 더 좋은 방법이 있습니까?
이 질문은 이것으로 문제를 많이 공유 한 . 나는 당신이 그것을 보도록 권장합니다.
특정 문제에 대해 다음이 작동해야합니다 (사용하지 않으므로 Core
일부 조정해야 할 수 있습니다 Unix.getpid
. 추상 의 결과를 얻었 습니까?).
open Ctypes;;
open Foreign;;
module Proc : sig
val pidpath : int -> string
(** @raise [Unix.Unix_error] in case of error *)
end = struct
let pidpathinfo_maxsize = 1024 * 4
(* value of PROC_PIDPATHINFO_MAXSIZE.
N.B. this should not be hardcoded, see 1) in this answer
https://stackoverflow.com/questions/20851390 *)
let char_array_as_string a len =
(* This function should soon no longer be required see:
https://github.com/ocamllabs/ocaml-ctypes/pull/139 *)
let b = Buffer.create len in
for i = 0 to len -1 do Buffer.add_char b (Array.get a i) done;
Buffer.contents b
let pidpath =
foreign ~check_errno:true "proc_pidpath"
(int @-> ptr char @-> int @-> returning int)
let pidpath pid =
let path = Array.make char ~initial:'\x00' pidpathinfo_maxsize in
let len = pidpath pid (Array.start path) pidpathinfo_maxsize in
char_array_as_string path len
end
let () =
let print_pidpath pid =
try
let path = Proc.pidpath pid in
Format.printf "Pid %d: %s@." pid path;
with Unix.Unix_error (e, _, _) ->
Format.eprintf "Pid %d: %s@." pid (Unix.error_message e)
in
print_pidpath (Unix.getpid ());
print_pidpath (-10000 (* bogus *))
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다