2

We have (for all intents and purposes) something similar to the following C++ code.

calc.h

#pragma once

extern "C" {
    void doCalc(uint8_t** buffer);
}

calc.cpp

#include <cstdint>
#include "calc.h"

void doCalc(uint8_t** buffer) {
    uint8_t lb[256];

    for (int i = 0; i < 256; i++) {
        lb[i] = i;
    }

    *buffer = new uint8_t[256];

    std::memcpy(*buffer, lb, 256);
}

We need to call this method from Go, but unsure how to construct the buffer variable on the Go side to pass in (seeing as the length is unknown prior to calling - the 256 in the C++ function should be considered unknown).

4
  • C or C++? They are two very different languages, and might need different setup for the external calls tro be possible. Commented May 25, 2022 at 12:08
  • Thanks, I saw in the title I made it C, my bad. This would be C++. Commented May 25, 2022 at 12:10
  • There are a few problems with your C++ function: The first is that you should not use malloc in C++, not even for simple buffers. Use new[] instead; The second problem is that the argument variable buffer is a local variable within the function, and whose life-time ends when the function returns. If you want to modify the variable inside the function you either need to pass it by reference or return it; Thirdly, to even be able to call the function you need to declare it as extern "C". Commented May 25, 2022 at 12:15
  • Ah yes (it has been a few years since I have done C++). Let me update the question. Commented May 25, 2022 at 12:23

2 Answers 2

1

I've made a slightly different example that fits your use case:

package main

/*
#include <stdio.h>

void print_words(int count, char** words) {
    for (int i = 0; i < count; i += 1) {
        printf(words[i]);
    }
}
*/
import "C"
import "unsafe"

func main() {
    words := make([]*C.char, 2)

    words[0] = C.CString("Hello ")
    words[1] = C.CString("World\n")

    C.print_words((C.int)(len(words)), (**C.char)(unsafe.Pointer(&words[0])))
}
Sign up to request clarification or add additional context in comments.

Comments

0

Based off @Jacob Wischnat 's answer (thanks!), I was able to get it working for my example:

func main() {
    cBuf := make([]*C.uint8_t, 1)

    C.doCalc((**C.uint8_t)(unsafe.Pointer(&cBuf[0])))
    
    gBuf := C.GoBytes(unsafe.Pointer(cBuf[0]), 256)

    // ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.