Crystal: Referencing C enums in lib wrappers

Created on 23 Aug 2017  Â·  3Comments  Â·  Source: crystal-lang/crystal

I'm trying to write a Crystal wrapper around libevent, and I wondered how to approach its enums that are named as all lower-case, for instance:

enum ev_http_request_error:

I tried the following:

@[Link("event")]
lib LibEvent
  # <snip>
  enum evhttp_request_error
    EVREQ_HTTP_TIMEOUT,
    EVREQ_HTTP_EOF,
    EVREQ_HTTP_INVALID_HEADER,
    EVREQ_HTTP_BUFFER_ERROR,
    EVREQ_HTTP_DATA_TOO_LONG
  end
end

but this fails because evhttp_request_error doesn't fit the grammar for a Crystal constant.
How should I address this?

question

All 3 comments

Just change the name to whatever you want. The only thing that has to be named the same between crystal and C is functions. That's the only kind of name which is in the symbols and the linker had to deal with. You can provide two names for lib functions, so that you can have a nice crystal name bound to an ugly external symbol.

Also may I ask why you're binding libevent. We use libevent in the fiber scheduler for the stdlib and I can't imagine 2 event loops ending well. If you want a fast http server use the one already in the stdlib.

@RX14 thanks for the clarification – and on reflection, this makes sense. I realise that Crystal's going to care much more about the types than C will :)

The reason I was considering binding libevent was for an http _client_, not a server. I was trying to do an HTTP client that called out to multiple services concurrently and then combined the results, but the average duration of the requests seems longer than it should be if the requests were non-blocking…

I was trying to do an HTTP client that called out to multiple services concurrently and then combined the results, but the average duration of the requests seems longer than it should be if the requests were non-blocking

Are you saying you tried to use HTTP::Client but it appeared to you as if the requests were non-blocking? If that's the case, some code/examples would be useful to see what's going on. However, this issue tracker isn't really the best method to get help and support, perhaps you could pop in on IRC or gitter and get some help there?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

asterite picture asterite  Â·  71Comments

xtagon picture xtagon  Â·  132Comments

asterite picture asterite  Â·  70Comments

asterite picture asterite  Â·  60Comments

asterite picture asterite  Â·  139Comments