Skip to content
This repository has been archived by the owner on Jul 4, 2023. It is now read-only.

Latest commit

 

History

History
110 lines (82 loc) · 2.69 KB

4_curl_request.md

File metadata and controls

110 lines (82 loc) · 2.69 KB

4 - Curl based HTTP requests

Task

Send an HTTP request to obtain your IP (e.g. GET https://api.ipify.org). The application should print out the IP to standard output.

The solution can be based on C code example for handling HTTP requests using libcurl from here.

Majority of the code is already provided. Let's take a look on how we have linked Curl in com.tapad.curl.CCurl.

To accomplish the task you must implement function writing the body of response into memory buffer in class com.tapad.curl.CurlHttp.

Note on interoperability with C

Basic memory management

Zone { implicit z =>
  val buffer = alloc[Byte](n)
}

or well-known stdlib and libc functions:

def malloc(size: CSize): Ptr[Byte]
def calloc(num: CSize, size: CSize): Ptr[Byte]
def realloc(ptr: Ptr[Byte], newSize: CSize): Ptr[Byte]
def free(ptr: Ptr[Byte]): Unit
def memcpy(dst: RawPtr, src: RawPtr, count: CSize): RawPtr

Handling Strings

def toCString(str: String)(implicit z: Zone): CString
def fromCString(cstr: CString,
                charset: Charset = Charset.defaultCharset()): String
val msg: CString = c"Hello, world!"

Extern objects and linking libraries

@native.link("mylib")
@native.extern
object mylib {
  def f(): Unit = native.extern
}

Structs

type MyStructWith2Fields = CStruct2[CString, CString]

Pointers:

Operation C syntax Scala Syntax
As function argument char* Ptr[CChar]
Load value *ptr !ptr
Store value *ptr = value !ptr = value
Load at index ptr[i] ptr(i)
Store at index ptr[i] = value ptr(i) = value
Load a field ptr->name !ptr._N
Store a field ptr->name = value !ptr._N = value

Function pointers

The following signature in C:

void foo(void (* f)(char *));

can be declared as following in Scala:

def foo(f: CFunctionPtr1[CString, Unit]): Unit = native.extern

To pass a Scala function to CFunctionPtr1, you need to use the conversion function CFunctionPtr.fromFunction1():

def f(s: CString): Unit = ???
foo(CFunctionPtr.fromFunction1(f))
For more details, go to the documentation.