Passing a string to a C library from OCaml using Ctypes and Foreign

Viewed 665

I'm really new to OCaml, and wanted to try and do some work with pcap as a way of getting started, only, there doesn't seem to be a maintained library for it. After looking at the awesome Real World OCaml book, I figured I'd give writing a binding a go.

Here's the (poor) code snippet:

open Ctypes
open Foreign
open PosixTypes
let char_ptr = "                 "

let pcap_lookupdev = foreign "pcap_lookupdev" (string @-> returning string_opt)

let result = pcap_lookupdev char_ptr

let test2 =
    match result with
    | None -> char_ptr
    | Some str -> str
 ;;

print_string test2;;

The pcap_lookupdev function returns either a string containing the device name or a null pointer. That bit seems to work fine (although I know my code is hardly idiomatic).

When writing this in C, you need to provide a character array to hold any error messages. So if a null pointer is returned, you should fail with the reason held in this character array. This character array should be "PCAP_ERRBUF_SIZE" long. However I can't figure out two things:

  1. How to pull that constant size from the C library and create a string that size
  2. Pass the string correctly to the function so that it gets correctly populated with the error message

Any help most gratefully appreciated :)

1 Answers
Related