Перейти на головну

Go, C та С++

В Go можна застосовувати функції та класи описані на С і С++. Для цього під WINDOWS потрібен mingw з GCC компіляторами С і С++. Для підключення h файлів, їх необхідно внести перед імпортом С в закоментованому вигляді.

Файл main.go:package main

// #include <example.h>
// #include "junk.h"
import "C"
import "fmt"
import "time"

func makeTimestamp() int64 {
	return time.Now().UnixNano() / int64(time.Millisecond)
}
func main() {
	a := makeTimestamp()
	fmt.Printf("%d \n", a)
	i := 0
	for i <= 1000000000 {
		i++
	}
	b := makeTimestamp() - a
	fmt.Printf("%d \n", b)
	C.x(10)
	C.xc(10)
	fmt.Printf("Done\n")
}
         

Файл example.h:int xc(int);         
Файл example.c:#include <stdio.h>
#include "windows.h"

int xc( int y ) {
	SYSTEMTIME time;
	GetSystemTime(&time);
	WORD millis1 = (time.wSecond * 1000) + time.wMilliseconds;
	
	//do something...
	for (double count = 0; count <= 1000000000;) {
		 count++;
	}
	
	//SYSTEMTIME time;
	GetSystemTime(&time);
	WORD millis2 = (time.wSecond * 1000) + time.wMilliseconds;

	printf("%d \n", millis2-millis1);
    return y+1;
}         
Файл junk.h:#ifndef __JUNK_HPP__
#define __JUNK_HPP__

#ifdef __cplusplus
extern "C" {
#endif

    int x(int y);
#ifdef __cplusplus
}
#endif

#endif         
Файл junk.cpp:#include 
#include <stdio.h>
#include <iostream>
#include "windows.h"

int x(int y) {
    std::cout << "hello" << std::endl;
    //printf("Hello World\n");
	
	SYSTEMTIME time;
	GetSystemTime(&time);
	WORD millis1 = (time.wSecond * 1000) + time.wMilliseconds;
	
	//do something...
	for (double count = 0; count <= 1000000000;) {
		 count++;
	}
	
	//SYSTEMTIME time;
	GetSystemTime(&time);
	WORD millis2 = (time.wSecond * 1000) + time.wMilliseconds;

	printf("%d \n", millis2-millis1);


	unsigned __int64 freq;
	QueryPerformanceFrequency((LARGE_INTEGER*)&freq);
	double timerFrequency = (1.0/freq);
	
	unsigned __int64 startTime;
	QueryPerformanceCounter((LARGE_INTEGER *)&startTime);
	
	for (double count = 0; count <= 1000000000;) {
		 count++;
	}
	
	unsigned __int64 endTime;
	QueryPerformanceCounter((LARGE_INTEGER *)&endTime);
	double timeDifferenceInMilliseconds = ((endTime-startTime) * timerFrequency);

	printf("%d \n",timeDifferenceInMilliseconds);

    return y;
}