-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibtextcat.go
66 lines (59 loc) · 1.18 KB
/
libtextcat.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
A wrapper for libtextcat.
See: http://software.wise-guys.nl/libtextcat/
*/
package libtextcat
/*
#cgo LDFLAGS: -lexttextcat
#include <libexttextcat/textcat.h>
#include <stdlib.h>
#include <string.h>
void *tc_init(const char *configfile) {
return textcat_Init(configfile);
}
void tc_done(void *h) {
textcat_Done(h);
}
char *tc_classify(void *h, const char *buffer) {
size_t size;
size = strlen(buffer);
return textcat_Classify(h, buffer, size);
}
*/
import "C"
import (
"errors"
"runtime"
"unsafe"
)
type Textcat struct {
h unsafe.Pointer
isOpen bool
}
func NewTextcat(configfile string) (t *Textcat, e error) {
t = &Textcat{}
cs := C.CString(configfile)
t.h = C.tc_init(cs)
C.free(unsafe.Pointer(cs))
if uintptr(t.h) == 0 {
e = errors.New("Init libtextcat failed for config file \"" + configfile + "\"")
} else {
t.isOpen = true
}
runtime.SetFinalizer(t, (*Textcat).Close)
return
}
func (t *Textcat) Classify(s string) string {
if !t.isOpen {
panic("Textcat is closed")
}
cs := C.CString(s)
defer C.free(unsafe.Pointer(cs))
return C.GoString(C.tc_classify(t.h, cs))
}
func (t *Textcat) Close() {
if t.isOpen {
C.tc_done(t.h)
t.isOpen = false
}
}