Как построить C++ так, чтобы его можно было вызывать из JS с аргументами?Javascript

Форум по Javascript
Ответить
Anonymous
 Как построить C++ так, чтобы его можно было вызывать из JS с аргументами?

Сообщение Anonymous »

Я делаю небольшой проект по изучению C++ и веб-технологий. Я работаю на Python, поэтому не совсем понимаю, что этот исходный код нужно сначала собрать, а затем превратить в .exe, пока, так что извините, если это глупая ошибка новичка.
Вот функция на моем сервере:

Код: Выделить всё

// generate maze
app.get('/api/generate-maze', (req, res) => {

const width = 11; // TODO: get data from front end
const height = 11;
const startX = 1;
const startY = 1;
const endX = 9;
const endY = 9;

// Run C++ program
const cppProcess = spawn('../cpp/maze_generator.exe', [width, height, startX, startY, endX, endY])

// When the C++ program finishes:
cppProcess.on('close', (code) => {
// Read the JSON file C++ created
const mazeData = fs.readFileSync('public/data/maze.json');

// Send it to browser
res.json(JSON.parse(mazeData));
});

// Handle errors
cppProcess.on('error', (err) => {
res.status(500).json({ error: 'C++ program failed' });
});
});
а это C++:

Код: Выделить всё

#include 
#include 
#include 
#include 
#include 
#include 

class MazeGenerator {
private:
// member variables
int width, height;
std::vector maze;
std::mt19937 rng;

public:
MazeGenerator(int w, int h) : width(w), height(h), rng(std::time(nullptr)) {
// constructor (like def __init__())
// This means:
// width = w;         (set width to the w parameter)
// height = h;        (set height to the h parameter)
// rng = std::time(nullptr);  (seed random generator with current time)

// Then run the constructor body:
maze = std::vector(height, std::vector(width, 1)); // height x width matrix containing 1s
}

void generateMaze(std::pair start = {1,1}, std::pair end = {-1,-1}) {

// If end is {-1,-1}, calculate the real end
if (end.first == -1) {
end = {height-2, width-2}; // bottom-right corner
}

std::stack stack;
maze[start.first][start.second] = 0;
stack.push(start);

while (!stack.empty()) {
auto [x, y] = stack.top();

std::vector neighbors;
// Check all 4 directions (2 cells away to leave walls between)
if (x + 2 < width - 1 && maze[y][x + 2] == 1) neighbors.push_back({x + 2, y});
if (x - 2 > 0 && maze[y][x - 2] == 1) neighbors.push_back({x - 2, y});
if (y + 2 < height - 1 && maze[y + 2][x] == 1) neighbors.push_back({x, y + 2});
if (y - 2 > 0 && maze[y - 2][x] == 1) neighbors.push_back({x, y - 2});

if (!neighbors.empty()) {
// Choose random neighbor
auto [nx, ny] = neighbors[rng() % neighbors.size()];

// Remove wall between current and neighbor
maze[(y + ny) / 2][(x + nx) / 2] = 0;
maze[ny][nx] = 0;

stack.push({nx, ny});
} else {
stack.pop();
}
}

maze[start.first][start.second] = 2; // Mark as start
maze[end.first][end.second] = 3;     // Mark as end
}

void saveToJSON(const std::string& filename) {
std::ofstream file(filename);
file 

Подробнее здесь: [url]https://stackoverflow.com/questions/79821643/how-to-build-c-such-that-it-can-be-called-from-js-with-arguments[/url]
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»