My project is a c++ CLR/CLI, I have some PNG images in my Resource Files and I want to change the BackgroundImage of a System::Windows::Forms::Button when the button is clicked, my code below:
#include <Windows.h>
#include "resource.h"
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
HBITMAP hBitMap = (HBITMAP) LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(IDB_PNG2), IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
Bitmap^ bitMap = Bitmap::FromHbitmap((IntPtr) hBitMap);
DeleteObject(hBitMap);
button1->BackgroundImage = (System::Drawing::Image^) bitMap;
}
Here's my resource.h:
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by Disneyy.rc
//
#define IDB_PNG1 101
#define IDB_PNG2 102
#define IDB_PNG3 103
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 104
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
When compiling I'm getting this error:
1>MyForm.obj : error LNK2028: unresolved token (0A000036) "extern "C" void * __stdcall LoadImageW(struct HINSTANCE__ *,wchar_t const *,unsigned int,int,int,unsigned int)" (?LoadImageW##$$J224YGPAXPAUHINSTANCE__##PB_WIHHI#Z) referenced in function "private: void __clrcall Disneyy::MyForm::button1_Click(class System::Object ^,class System::EventArgs ^)" (?button1_Click#MyForm#Disneyy##$$FA$AAMXP$AAVObject#System##P$AAVEventArgs#4##Z)
1>MyForm.obj : error LNK2028: unresolved token (0A00003F) "extern "C" int __stdcall DeleteObject(void *)" (?DeleteObject##$$J14YGHPAX#Z) referenced in function "private: void __clrcall Disneyy::MyForm::button1_Click(class System::Object ^,class System::EventArgs ^)" (?button1_Click#MyForm#Disneyy##$$FA$AAMXP$AAVObject#System##P$AAVEventArgs#4##Z)
1>MyForm.obj : error LNK2019: unresolved external symbol "extern "C" void * __stdcall LoadImageW(struct HINSTANCE__ *,wchar_t const *,unsigned int,int,int,unsigned int)" (?LoadImageW##$$J224YGPAXPAUHINSTANCE__##PB_WIHHI#Z) referenced in function "private: void __clrcall Disneyy::MyForm::button1_Click(class System::Object ^,class System::EventArgs ^)" (?button1_Click#MyForm#Disneyy##$$FA$AAMXP$AAVObject#System##P$AAVEventArgs#4##Z)
1>MyForm.obj : error LNK2019: unresolved external symbol "extern "C" int __stdcall DeleteObject(void *)" (?DeleteObject##$$J14YGHPAX#Z) referenced in function "private: void __clrcall Disneyy::MyForm::button1_Click(class System::Object ^,class System::EventArgs ^)" (?button1_Click#MyForm#Disneyy##$$FA$AAMXP$AAVObject#System##P$AAVEventArgs#4##Z)
EDIT:
Ok I fixed it by adding User32.lib to Additional Dependencies also specifying the Entry Point as main. However there's something wrong with this line:
HBITMAP hBitMap = (HBITMAP) LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(IDB_PNG2), IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
Now I'm getting this error:
First-chance exception at 0x77130c3f in Disneyy.exe: 0xC0000005: Access violation reading location 0x00000066.
A first chance exception of type 'System.AccessViolationException' occurred in Disneyy.exe
An unhandled exception of type 'System.AccessViolationException' occurred in Disneyy.exe
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
EDIT:
Once again I fixed it by changing IMAGE_BITMAP to BI_PNG, but now a new error comes up at line: Bitmap^ bitMap = Bitmap::FromHbitmap((IntPtr) hBitMap);
A first chance exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll
An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll
Additional information: A generic error occurred in GDI+.
Finally after hours and hours of research I found an adapted solution which works just fine!
This solution is a combination of Giuseppe Pischedda's answer: https://www.codeproject.com/Articles/17996/Load-JPEG-images-from-DLL-with-LoadResource-in-Man
and Bordon's answer: https://social.msdn.microsoft.com/Forums/de-DE/c8dea6f9-0564-49d6-9782-117207031140/loadfromresource-fails-for-loading-png-files-from-resource?forum=vcmfcatl
adapted by me for PNG images:
public: System::Drawing::Image^ getImageFromRes(long resource_ID) {
// Function getImageFromRes
// A function for loading PNG images from resources in C++ CLR/CLI
// Copyright (C) Giuseppe Pischedda 2007 for most code
// and a little part of this code by Bordon and adapted by me for PNG images in C++ CLR/CLI.
//Load the resource module:
HMODULE hInst = NULL;
// Find the resource using the resource ID from file "resource.h"
HRSRC hResource = ::FindResource(hInst, MAKEINTRESOURCE(resource_ID), L"PNG");
if (!hResource) return nullptr;
// Load the resource and save the total size.
DWORD Size = SizeofResource(hInst, hResource);
HGLOBAL MemoryHandle = LoadResource(hInst, hResource);
if (MemoryHandle == NULL) return nullptr;
//Create a cli::array of byte with size = total size + 2
cli::array<BYTE>^ MemPtr = gcnew array<BYTE>(Size + 2);
//Cast from LPVOID to char *
char *lkr = (char *) (LockResource(MemoryHandle));
//Copy from unmanaged memory to managed array
System::Runtime::InteropServices::Marshal::Copy((IntPtr) lkr, MemPtr, 0, Size);
// Create a new MemoryStream with size = MemPtr
System::IO::MemoryStream^ stream = gcnew System::IO::MemoryStream(MemPtr);
//Write in the MemoryStream
stream->Write(MemPtr, 0, Size);
//Set the position for read the stream
stream->Position = 0;
//Free allocated resources
FreeLibrary(hInst);
//Create an Image abstract class pointer
System::Drawing::Image^ ptrPNG;
//Assign the stream to abstract class pointer
ptrPNG = System::Drawing::Image::FromStream(stream);
return ptrPNG;
}
Usage:
System::Drawing::Image^ image = getImageFromRes(IDB_PNG2);
if (image != nullptr) button1->BackgroundImage = image;
Related
Basically I am trying create a simple FileSystem MiniFilter Driver where I can modify a notepad file from writing. Following this tutorial. So I created a project in visual studio which is type Filter Driver: NDIS. here is the full code:
/*++
Module Name:
Filter.c
Abstract:
Sample NDIS Lightweight filter driver
--*/
#include "precomp.h"
PFLT_FILTER FilterHandle = NULL;
NTSTATUS MiniUnload(FLT_FILTER_UNLOAD_FLAGS Flags);
FLT_POSTOP_CALLBACK_STATUS MiniPostCreate(PFLT_CALLBACK_DATA Data, PCFLT_RELATED_OBJECTS FltObjects, PVOID* CompletionContext, FLT_POST_OPERATION_FLAGS flags);
FLT_PREOP_CALLBACK_STATUS MiniPreCreate(PFLT_CALLBACK_DATA Data, PCFLT_RELATED_OBJECTS FltObjects, PVOID* CompletionContext);
FLT_PREOP_CALLBACK_STATUS MiniPreWrite(PFLT_CALLBACK_DATA Data, PCFLT_RELATED_OBJECTS FltObjects, PVOID* CompletionContext);
const FLT_OPERATION_REGISTRATION Callbacks[] = {
{IRP_MJ_CREATE,0,MiniPreCreate,MiniPostCreate},
{IRP_MJ_WRITE,0,MiniPreCreate,NULL},
{IRP_MJ_OPERATION_END}
};
const FLT_REGISTRATION FilterRegistration = {
sizeof(FLT_REGISTRATION),
FLT_REGISTRATION_VERSION,
0,
NULL,
Callbacks,
MiniUnload,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL
};
NTSTATUS MiniUnload(FLT_FILTER_UNLOAD_FLAGS Flags) {
KdPrint(("driver unload \r\n"));
FltUnregisterFilter(FilterHandle);
return STATUS_SUCCESS;
}
FLT_POSTOP_CALLBACK_STATUS MiniPostCreate(PFLT_CALLBACK_DATA Data, PCFLT_RELATED_OBJECTS FltObjects, PVOID* CompletionContext, FLT_POST_OPERATION_FLAGS flags) {
KdPrint(("Post Create is running \r\n"));
return FLT_POSTOP_FINISHED_PROCESSING;
}
FLT_PREOP_CALLBACK_STATUS MiniPreCreate(PFLT_CALLBACK_DATA Data, PCFLT_RELATED_OBJECTS FltObjects, PVOID* CompletionContext) {
PFLT_FILE_NAME_INFORMATION FileNameInfo;
NTSTATUS status;
WCHAR Name[300] = { 0 };
status = FltGetFileNameInformation(Data, FLT_FILE_NAME_NORMALIZED | FLT_FILE_NAME_QUERY_DEFAULT, &FileNameInfo);
if (NT_SUCCESS(status)) {
status = FltParseFileNameInformation(FileNameInfo);
if (NT_SUCCESS(status)) {
if (FileNameInfo->Name.MaximumLength < 260) {
RtlCopyMemory(Name, FileNameInfo->Name.Buffer, FileNameInfo->Name.MaximumLength);
KdPrint(("CreateFile: %ws \r\n", Name));
}
}
FltReleaseFileNameInformation(FileNameInfo);
}
return FLT_PREOP_SUCCESS_WITH_CALLBACK;
}
FLT_PREOP_CALLBACK_STATUS MiniPreWrite(PFLT_CALLBACK_DATA Data, PCFLT_RELATED_OBJECTS FltObjects, PVOID* CompletionContext) {
PFLT_FILE_NAME_INFORMATION FileNameInfo;
NTSTATUS status;
WCHAR Name[300] = { 0 };
status = FltGetFileNameInformation(Data, FLT_FILE_NAME_NORMALIZED | FLT_FILE_NAME_QUERY_DEFAULT, &FileNameInfo);
if (NT_SUCCESS(status)) {
status = FltParseFileNameInformation(FileNameInfo);
if (NT_SUCCESS(status)) {
if (FileNameInfo->Name.MaximumLength < 260) {
RtlCopyMemory(Name, FileNameInfo->Name.Buffer, FileNameInfo->Name.MaximumLength);
_wcsupr(Name);
if (wcsstr(Name, L"OPENME.TXT") != NULL) {
KdPrint(("Write File: %ws Blocked \r\n", Name));
Data->IoStatus.Status = STATUS_INVALID_PARAMETER;
Data->IoStatus.Information = 0;
FltReleaseFileNameInformation(FileNameInfo);
return FLT_PREOP_COMPLETE;
}
KdPrint(("CreateFile: %ws \r\n", Name));
}
}
FltReleaseFileNameInformation(FileNameInfo);
}
return FLT_PREOP_SUCCESS_WITH_CALLBACK;
}
NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) {
NTSTATUS status;
status = FltRegisterFilter(DriverObject, &FilterRegistration, &FilterHandle);
if (NT_SUCCESS(status)) {
status = FltStartFiltering(FilterHandle);
if (!NT_SUCCESS(status)) {
FltUnregisterFilter(FilterHandle);
}
}
return status;
}
The header files have been to precomp.h as below:
#pragma warning(disable:4201) //nonstandard extension used : nameless struct/union
#pragma warning(disable:4100)
#include <fltKernel.h>
#include <dontuse.h>
#include <suppress.h>
#include <ndis.h>
#include <filteruser.h>
#include <ntddk.h>
#include "flt_dbg.h"
#include "filter.h"
Everything else is default.
Project configuration is Active(x64) under properties.
With all of that I am getting below errors:
Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external symbol FltGetFileNameInformation referenced in function MiniPreCreate default C:\Users\Abdul\source\repos\default\default\filter.obj 1
Warning 1324 [Version] section should specify PnpLockdown=1 to prevent external apps from modifying installed driver files. default C:\Users\Abdul\source\repos\default\default\default.inf 8
Error LNK2019 unresolved external symbol FltRegisterFilter referenced in function DriverEntry default C:\Users\Abdul\source\repos\default\default\filter.obj 1
Error LNK2019 unresolved external symbol FltUnregisterFilter referenced in function MiniUnload default C:\Users\Abdul\source\repos\default\default\filter.obj 1
Error LNK2019 unresolved external symbol FltStartFiltering referenced in function DriverEntry default C:\Users\Abdul\source\repos\default\default\filter.obj 1
Error LNK2019 unresolved external symbol FltReleaseFileNameInformation referenced in function MiniPreCreate default C:\Users\Abdul\source\repos\default\default\filter.obj 1
Error LNK2019 unresolved external symbol FltParseFileNameInformation referenced in function MiniPreCreate default C:\Users\Abdul\source\repos\default\default\filter.obj 1
Error LNK2001 unresolved external symbol FilterDriverHandle default C:\Users\Abdul\source\repos\default\default\device.obj 1
Error LNK2001 unresolved external symbol FilterDriverObject default C:\Users\Abdul\source\repos\default\default\device.obj 1
Error LNK2001 unresolved external symbol NdisFilterDeviceHandle default C:\Users\Abdul\source\repos\default\default\device.obj 1
Error LNK2001 unresolved external symbol NdisDeviceObject default C:\Users\Abdul\source\repos\default\default\device.obj 1
Error LNK2001 unresolved external symbol FilterListLock default C:\Users\Abdul\source\repos\default\default\device.obj 1
Error LNK2001 unresolved external symbol FilterModuleList default C:\Users\Abdul\source\repos\default\default\device.obj 1
Error LNK1120 12 unresolved externals default C:\Users\Abdul\source\repos\default\x64\Debug\default.sys 1
Can Anyone guide on what am I doing wrong?
I ran into the same issue. For me, the problem was that the mini-filter template was not showing in the templates listing for new projects and so I had to create it from scratch and I inevitably missed something. After cross-checking the linker options against the minifilter projects provided by Microsoft as reference (check here) I realized that fltMgr.lib has to be specifically provided to the linker. In order to do that right-click on the project in the "Solution Explorer" left pane. Then go to Properties->Linker->Input->Additional Dependencies. Add $(DDK_LIB_PATH)\fltMgr.lib to the list of additional dependencies and rebuild your project!
I hope this does it for you, but like the Microsoft documentation points out LNK2019 can be caused by lots of other problems with your configuration.
So I'm reading "Beginning Game Programming Third Edition" by Jonathan S. Harbour, and I've gotten to the point where he teaches us how to use Direct Sound. The book uses it's own DirectSound.h and DirectSound.cpp files, which were from a previous release of the DirectX SDK, but when I try to compile I get the "LNK2019: unresolved external symbol" error.
1>DirectSound.obj : error LNK2019: unresolved external symbol
_DXTraceA#20 referenced in function "public: long thiscall CSoundManager::Initialize(struct HWND *,unsigned long)"
(?Initialize#CSoundManager##QAEJPAUHWND__##K#Z)
1>DirectSound.obj : error LNK2019: unresolved external symbol
_DirectSoundCreate8#12 referenced in function "public: long thiscall CSoundManager::Initialize(struct HWND *,unsigned long)"
(?Initialize#CSoundManager##QAEJPAUHWND__##K#Z)
I have not implemented any Direct Sound code in my project as yet, the mere presence of these files causes the project to not compile. Without them, the project compiles and runs perfectly.
#ifndef DSUTIL_H
#define DSUTIL_H
#include <windows.h>
#include <mmsystem.h>
#include <mmreg.h>
#include <dsound.h>
class CSoundManager;
class CSound;
class CStreamingSound;
class CWaveFile;
#define WAVEFILE_READ 1
#define WAVEFILE_WRITE 2
#define DSUtil_StopSound(s) { if(s) s->Stop(); }
#define DSUtil_PlaySound(s) { if(s) s->Play( 0, 0 ); }
#define DSUtil_PlaySoundLooping(s) { if(s) s->Play( 0, DSBPLAY_LOOPING ); }
//-----------------------------------------------------------------------------
// Name: class CSoundManager
// Desc:
//-----------------------------------------------------------------------------
class CSoundManager
{
protected:
LPDIRECTSOUND8 m_pDS;
public:
CSoundManager();
~CSoundManager();
HRESULT Initialize(HWND hWnd, DWORD dwCoopLevel);
inline LPDIRECTSOUND8 GetDirectSound() { return m_pDS; }
HRESULT SetPrimaryBufferFormat( DWORD dwPrimaryChannels, DWORD dwPrimaryFreq, DWORD dwPrimaryBitRate );
HRESULT Create( CSound** ppSound, LPTSTR strWaveFileName, DWORD dwCreationFlags = 0, GUID guid3DAlgorithm = GUID_NULL, DWORD dwNumBuffers = 1 );
};
//-----------------------------------------------------------------------------
// Name: class CSound
// Desc: Encapsulates functionality of a DirectSound buffer.
//-----------------------------------------------------------------------------
class CSound
{
protected:
LPDIRECTSOUNDBUFFER* m_apDSBuffer;
DWORD m_dwDSBufferSize;
CWaveFile* m_pWaveFile;
DWORD m_dwNumBuffers;
DWORD m_dwCreationFlags;
HRESULT RestoreBuffer( LPDIRECTSOUNDBUFFER pDSB, BOOL* pbWasRestored );
public:
CSound( LPDIRECTSOUNDBUFFER* apDSBuffer, DWORD dwDSBufferSize, DWORD dwNumBuffers, CWaveFile* pWaveFile, DWORD dwCreationFlags );
virtual ~CSound();
HRESULT FillBufferWithSound( LPDIRECTSOUNDBUFFER pDSB, BOOL bRepeatWavIfBufferLarger );
LPDIRECTSOUNDBUFFER GetFreeBuffer();
HRESULT Play( DWORD dwPriority = 0, DWORD dwFlags = 0, LONG lVolume = 0, LONG lFrequency = -1, LONG lPan = 0 );
HRESULT Stop();
HRESULT Reset();
BOOL IsSoundPlaying();
};
//-----------------------------------------------------------------------------
// Name: class CWaveFile
// Desc: Encapsulates reading or writing sound data to or from a wave file
//-----------------------------------------------------------------------------
class CWaveFile
{
public:
WAVEFORMATEX* m_pwfx; // Pointer to WAVEFORMATEX structure
HMMIO m_hmmio; // MM I/O handle for the WAVE
MMCKINFO m_ck; // Multimedia RIFF chunk
MMCKINFO m_ckRiff; // Use in opening a WAVE file
DWORD m_dwSize; // The size of the wave file
MMIOINFO m_mmioinfoOut;
DWORD m_dwFlags;
BOOL m_bIsReadingFromMemory;
BYTE* m_pbData;
BYTE* m_pbDataCur;
ULONG m_ulDataSize;
CHAR* m_pResourceBuffer;
protected:
HRESULT ReadMMIO();
HRESULT WriteMMIO( WAVEFORMATEX *pwfxDest );
public:
CWaveFile();
~CWaveFile();
HRESULT Open( LPTSTR strFileName, WAVEFORMATEX* pwfx, DWORD dwFlags );
HRESULT Close();
HRESULT Read( BYTE* pBuffer, DWORD dwSizeToRead, DWORD* pdwSizeRead );
HRESULT Write( UINT nSizeToWrite, BYTE* pbData, UINT* pnSizeWrote );
DWORD GetSize();
HRESULT ResetFile();
WAVEFORMATEX* GetFormat() { return m_pwfx; };
};
#endif // DSUTIL_H
///////////////////////////////////////////////////////////////////////////////
// The function that causes the error
HRESULT CSoundManager::Initialize(HWND hWnd, DWORD dwCoopLevel)
{
HRESULT hr;
SAFE_RELEASE(m_pDS);
// Create IDirectSound using the primary sound device
if(FAILED(hr = DirectSoundCreate8(NULL, &m_pDS, NULL)))
return DXTRACE_ERR(TEXT("DirectSoundCreate8"), hr);
// Set DirectSound coop level
if( FAILED( hr = m_pDS->SetCooperativeLevel( hWnd, dwCoopLevel ) ) )
return DXTRACE_ERR( TEXT("SetCooperativeLevel"), hr );
return S_OK;
}
Error LNK2019 is about adding a missing library - a typical problem. You should identify missing symbols, then identify library to additionally link, then add it using #pragma or via project settings.
Also as it's a beginner question, most likely Stack Overflow already has something closely related. Be always sure to run a search for it, compare code snippets to yours.
Application works in visual studio but release/debug exe does not
Which header should I include for DXTrace?
Related questions show that you need dsound.lib and dxerr.lib to be linked in.
I upgraded to Qt 5.5 and RegisterDeviceNotificationcall started to generate a link error and project doesn't built. It still builds with Qt 5.4 and I am using VS2010 compiler in both cases.
bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
MSG * msg = static_cast< MSG * > (message);
int msgType = msg->message;
if(msgType == WM_PAINT)
{
if(!msgp) //Only the first WM_PAINT
{
GUID InterfaceClassGuid = HID_CLASSGUID;
DEV_BROADCAST_DEVICEINTERFACE NotificationFilter;
ZeroMemory( &NotificationFilter, sizeof(NotificationFilter) );
NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
NotificationFilter.dbcc_classguid = InterfaceClassGuid;
HWND hw = (HWND) this->effectiveWinId(); //Main window handle
HDEVNOTIFY hDevNotify = RegisterDeviceNotification(hw,&NotificationFilter, DEVICE_NOTIFY_ALL_INTERFACE_CLASSES ); //DEVICE_NOTIFY_WINDOW_HANDLE);
msgp = true;
}
}
// i have more code here but the link error occurs in the above
}
I did include <windows.h> and <WinUser.h> but that didn't fix the link error.
The link error is:
mainwindow.obj:-1: error: LNK2019: unresolved external symbol __imp__RegisterDeviceNotificationW#12 referenced in function "private: virtual bool __thiscall MainWindow::nativeEvent(class QByteArray const &,void *,long *)" (?nativeEvent#MainWindow##EAE_NABVQByteArray##PAXPAJ#Z)
I tried to include modules in .pro files from here but none has made any difference.
According to RegisterDeviceNotification, you need to link with user32.lib. You can force this by adding this line to your .pro file:
LIBS += -luser32
However, this is a quite common Windows library that should have been linked in by default. Maybe you need to re-run qmake to ensure your makefiles are up to date?
I'm trying to convert a bmp image to a png one with this code:
#define WIN32_LEAN_AND_MEAN
#define _CRT_SECURE_NO_DEPRECATE
#include <png.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
void GetDesktopResolution(int& horizontal, int& vertical)
{
RECT desktop;
// Get a handle to the desktop window
const HWND hDesktop = GetDesktopWindow();
// Get the size of screen to the variable desktop
GetWindowRect(hDesktop, &desktop);
// The top left corner will have coordinates (0,0)
// and the bottom right corner will have coordinates
// (horizontal, vertical)
horizontal = desktop.right;
vertical = desktop.bottom;
}
typedef struct _RGBPixel {
uint8_t blue;
uint8_t green;
uint8_t red;
} RGBPixel;
/* Structure for containing decompressed bitmaps. */
typedef struct _RGBBitmap {
RGBPixel *pixels;
size_t width;
size_t height;
size_t bytewidth;
uint8_t bytes_per_pixel;
} RGBBitmap;
/* Returns pixel of bitmap at given point. */
#define RGBPixelAtPoint(image, x, y) \
*(((image)->pixels) + (((image)->bytewidth * (y)) \
+ ((x) * (image)->bytes_per_pixel)))
/* Attempts to save PNG to file; returns 0 on success, non-zero on error. */
int save_png_to_file(RGBBitmap *bitmap, const char *path)
{
FILE *fp = fopen(path, "wb");
png_structp png_ptr = NULL;
png_infop info_ptr = NULL;
size_t x, y;
png_uint_32 bytes_per_row;
png_byte **row_pointers = NULL;
if (fp == NULL) return -1;
/* Initialize the write struct. */
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (png_ptr == NULL) {
fclose(fp);
return -1;
}
/* Initialize the info struct. */
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL) {
png_destroy_write_struct(&png_ptr, NULL);
fclose(fp);
return -1;
}
/* Set up error handling. */
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp);
return -1;
}
/* Set image attributes. */
png_set_IHDR(png_ptr,
info_ptr,
bitmap->width,
bitmap->height,
8,
PNG_COLOR_TYPE_RGB,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT);
/* Initialize rows of PNG. */
bytes_per_row = bitmap->width * bitmap->bytes_per_pixel;
png_malloc(png_ptr, bitmap->height * sizeof(png_byte *));
for (y = 0; y < bitmap->height; ++y) {
uint8_t *row = (uint8_t *)png_malloc(png_ptr, sizeof(uint8_t)* bitmap->bytes_per_pixel);
row_pointers[y] = (png_byte *)row;
for (x = 0; x < bitmap->width; ++x) {
RGBPixel color = RGBPixelAtPoint(bitmap, x, y);
*row++ = color.red;
*row++ = color.green;
*row++ = color.blue;
}
}
/* Actually write the image data. */
png_init_io(png_ptr, fp);
png_set_rows(png_ptr, info_ptr, row_pointers);
png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
/* Cleanup. */
for (y = 0; y < bitmap->height; y++) {
png_free(png_ptr, row_pointers[y]);
}
png_free(png_ptr, row_pointers);
/* Finish writing. */
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp);
return 0;
}
int main()
{
RGBBitmap rgbbitmap;
int w, h;
GetDesktopResolution(w, h);
rgbbitmap.height = h;
rgbbitmap.width = w;
rgbbitmap.bytes_per_pixel = 1;
rgbbitmap.bytewidth = w / 100;
RGBPixel rgbpixel;
rgbpixel.blue = 100;
rgbpixel.green = 100;
rgbpixel.red = 100;
rgbbitmap.pixels = &rgbpixel;
save_png_to_file(&rgbbitmap, "abc.bmp");
return 0;
}
Executing this code triggers these errors :
LNK1120: 9 unresolved externals
LNK2019: unresolved external symbol _png_create_info_struct referenced in function "int __cdecl save_png_to_file(struct _RGBBitmap *,char const *)" (?save_png_to_file##YAHPAU_RGBBitmap##PBD#Z)
LNK2019: unresolved external symbol _png_create_write_struct referenced in function "int __cdecl save_png_to_file(struct _RGBBitmap *,char const *)" (?save_png_to_file##YAHPAU_RGBBitmap##PBD#Z)
LNK2019: unresolved external symbol _png_destroy_write_struct referenced in function "int __cdecl save_png_to_file(struct _RGBBitmap *,char const *)" (?save_png_to_file##YAHPAU_RGBBitmap##PBD#Z)
LNK2019: unresolved external symbol _png_free referenced in function "int __cdecl save_png_to_file(struct _RGBBitmap *,char const *)" (?save_png_to_file##YAHPAU_RGBBitmap##PBD#Z)
LNK2019: unresolved external symbol _png_init_io referenced in function "int __cdecl save_png_to_file(struct _RGBBitmap *,char const *)" (?save_png_to_file##YAHPAU_RGBBitmap##PBD#Z)
LNK2019: unresolved external symbol _png_malloc referenced in function "int __cdecl save_png_to_file(struct _RGBBitmap *,char const *)" (?save_png_to_file##YAHPAU_RGBBitmap##PBD#Z)
LNK2019: unresolved external symbol _png_set_IHDR referenced in function "int __cdecl save_png_to_file(struct _RGBBitmap *,char const *)" (?save_png_to_file##YAHPAU_RGBBitmap##PBD#Z)
LNK2019: unresolved external symbol _png_set_rows referenced in function "int __cdecl save_png_to_file(struct _RGBBitmap *,char const *)" (?save_png_to_file##YAHPAU_RGBBitmap##PBD#Z)
LNK2019: unresolved external symbol _png_write_png referenced in function "int __cdecl save_png_to_file(struct _RGBBitmap *,char const *)" (?save_png_to_file##YAHPAU_RGBBitmap##PBD#Z)
I'm not able to find how to fix these errors. Any brilliant suggestion, please?
I'm currently using Visual Studio Ultimate 2013 on a Windows 7 SP1 plateform.
Thanks a lot!
I think, you didn't linked your libraries, just included headers. This question anwers how you do it...
If not, there is plently of what can happen:
you are trying to call those functions with bad parameters
you included bad header file
you have mixed libraries or you are trying to link MinGW, VS2012/VS2012 compiled library to VS2013 compiler, since i don't know if they are compatible...
You can try to download png library, create VS2012 project and try to compile it. When you do, you should absolutely have no problems while linking...
I'm trying to follow Riemer's DirectX with C++ tutorial.
I have made a few changes, for example here I have made my InitializeDevice() function in a separate file (tdirect.cpp / tdirect.h).
When I press F5 to compile and run, the program works perfectly. But when I make a change to a value (e.g. 0xff00ffff to 0xff0000ff - cyan to blue) without choosing the "Rebuild" option I get a stream of errors in my console which prevent me from compiling the program. This is pretty annoying as you can imagine. It's as if it's compiling tdirect.cpp twice.
Here's the source code of tdirect.cpp, tdirect.h, and the relevant part from main.cpp (tdirect.h is only included from main.cpp, and basicvertex.h is only included from tdirect.cpp)
tdirect.cpp:
#include "tdirect.h"
#include "basicvertex.h"
IDirect3D9 *pD3D;
D3DPRESENT_PARAMETERS D3DParams;
LPDIRECT3DDEVICE9 InitializeDevice(HWND Wnd)
{
pD3D = Direct3DCreate9(D3D_SDK_VERSION);
if (pD3D == NULL)
{
MessageBox(Wnd, "DirectX is not installed.", "No DirectX!", MB_OK);
return NULL;
}
ZeroMemory(&D3DParams, sizeof(D3DPRESENT_PARAMETERS));
D3DParams.Windowed = TRUE;
D3DParams.SwapEffect = D3DSWAPEFFECT_DISCARD;
D3DParams.BackBufferFormat = D3DFMT_UNKNOWN;
LPDIRECT3DDEVICE9 pDevice;
if (FAILED(pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, Wnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &D3DParams, &pDevice)))
{
if (FAILED(pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_REF, Wnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &D3DParams, &pDevice)))
{
MessageBox(Wnd, "Failed to create reference device.", "No software device!", MB_OK);
}
else {
MessageBox(Wnd, "Falling back to software mode.", "No hardware device!", MB_OK);
}
}
return pDevice;
}
LPDIRECT3DVERTEXBUFFER9 vBuffer;
void Init(LPDIRECT3DDEVICE9 pDevice)
{
BASICVERTEX Vertices[3];
Vertices[0].x = 150;
Vertices[0].y = 100;
Vertices[0].weight = 1;
Vertices[0].colour = 0xffff0000;
Vertices[1].x = 350;
Vertices[1].y = 100;
Vertices[1].weight = 1;
Vertices[1].colour = 0xff00ff00;
Vertices[2].x = 250;
Vertices[2].y = 300;
Vertices[2].weight = 1;
Vertices[2].colour = 0xff00ffff;
if (FAILED(pDevice->CreateVertexBuffer(sizeof(BASICVERTEX)*3, 0, D3DFVF_XYZRHW | D3DFVF_DIFFUSE, D3DPOOL_DEFAULT, &vBuffer, NULL)))
{
MessageBox(NULL, "Failed to create vertex buffer", "Fail", MB_OK);
}
else {
void* pVertices;
if (FAILED(vBuffer->Lock(0, sizeof(BASICVERTEX)*3, (void**)&pVertices, 0)))
{
MessageBox(NULL, "Failed to lock vertex buffer", "Fail", MB_OK);
}
else {
memcpy(pVertices, Vertices, sizeof(BASICVERTEX)*3);
vBuffer->Unlock();
}
}
}
void DrawScene(LPDIRECT3DDEVICE9 pDevice)
{
pDevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0);
pDevice->BeginScene();
pDevice->SetStreamSource(0, vBuffer, 0, sizeof(BASICVERTEX));
pDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
pDevice->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);
pDevice->EndScene();
pDevice->Present(NULL, NULL, NULL, NULL);
}
tdirect.h:
#pragma once
#include <Windows.h>
main.cpp include part:
#include <Windows.h>
#include "dxheader.h"
#include "tdirect.cpp"
Compiler Errors:
1>Debug\tdirect.obj : warning LNK4042: object specified more than once; extras ignored
1>main.obj : error LNK2005: "struct IDirect3DDevice9 * __cdecl InitializeDevice(struct HWND__ *)" (?InitializeDevice##YAPAUIDirect3DDevice9##PAUHWND__###Z) already defined in tdirect.obj
1>main.obj : error LNK2005: "void __cdecl Init(struct IDirect3DDevice9 *)" (?Init##YAXPAUIDirect3DDevice9###Z) already defined in tdirect.obj
1>main.obj : error LNK2005: "void __cdecl DrawScene(struct IDirect3DDevice9 *)" (?DrawScene##YAXPAUIDirect3DDevice9###Z) already defined in tdirect.obj
1>main.obj : error LNK2005: "struct IDirect3DVertexBuffer9 * vBuffer" (?vBuffer##3PAUIDirect3DVertexBuffer9##A) already defined in tdirect.obj
1>main.obj : error LNK2005: "struct _D3DPRESENT_PARAMETERS_ D3DParams" (?D3DParams##3U_D3DPRESENT_PARAMETERS_##A) already defined in tdirect.obj
1>main.obj : error LNK2005: "struct IDirect3D9 * pD3D" (?pD3D##3PAUIDirect3D9##A) already defined in tdirect.obj
1>C:\Users\me\Documents\Visual Studio 2010\Projects\DirectX\Debug\DXStuff.exe : fatal error LNK1169: one or more multiply defined symbols found
Thanks in advance :)
You're including an implementation file from your main.cpp, so it's adding the functions in again. You can't do this:
#include "tdirect.cpp"
Instead you need to create a header file with the function prototypes so you can reference them...
Do you have these defined in your "tdirect.h" (this is what main.cpp should be including)?
LPDIRECT3DDEVICE9 InitializeDevice(HWND Wnd);
etc...